Labs ICT
โญ Pro Login

Strings

Strings are everywhere in PHP. Names, messages, emails, form input โ€” they're all strings. PHP gives you a rich set of tools to work with them, and understanding strings is essential before you can build anything useful.

You can define a string with single quotes 'like this' or double quotes "like this". And there's a difference.

Single vs Double Quotes

Double-quoted strings interpret variables and special escape characters. Single-quoted strings treat everything literally. If you put a $variable inside single quotes, you get the literal text $variable. Inside double quotes, PHP replaces it with the variable's value.


<?php
$name = "Bilal";

echo "Hello, $name!";   // Hello, Bilal!
echo 'Hello, $name!';   // Hello, $name!
?>
    
Try it Yourself โ†’

Double quotes also handle escape sequences like \n (new line) and \t (tab). Single quotes only recognize \\ (backslash) and \' (single quote).

Concatenation with the Dot Operator

To join strings together, use the dot operator .. It's PHP's string concatenation operator. Think of it as glue for text.


<?php
$first = "Bilal";
$last = "Idris";
$full = $first . " " . $last;

echo $full;
?>
    

You can also use the shorthand .= to append to an existing string:


<?php
$message = "Hello";
$message .= " World";
$message .= "!";

echo $message;
?>
    

Useful String Functions

PHP's standard library is packed with string functions. Here are the ones you'll reach for most often:


<?php
$text = "Hello PHP World";

echo strlen($text);            // 16 โ€” length of string
echo str_word_count($text);    // 3 โ€” number of words
echo strpos($text, "PHP");     // 6 โ€” position where "PHP" starts
echo str_replace("PHP", "Laravel", $text);  // Hello Laravel World
echo strtoupper($text);        // HELLO PHP WORLD
echo strtolower($text);        // hello php world
?>
    

strpos() is especially useful โ€” it returns the character position (0-indexed) of the first occurrence of a substring. If the substring isn't found, it returns false. That makes it perfect for checking if a string contains something.

๐Ÿงช Quick Quiz

Which operator is used to concatenate two strings in PHP?