PHP Strings
A string is a sequence of characters and is one of the most frequently used data types in any PHP application.
Creating strings
A string in PHP is simply text: letters, digits, spaces, and symbols grouped together. You can create a string in several ways, but the two you will use most often are single quotes and double quotes. The choice between them is not just style — it changes how PHP treats the characters inside. Single-quoted strings are taken almost literally, while double-quoted strings are parsed for variables and escape sequences.
Single and double quotes
<?php
$city = "Berlin";
$single = 'Weather in $city';
$double = "Weather in $city";
echo $single; // Weather in $city
echo "\n";
echo $double; // Weather in Berlin
?>In the example above, the single-quoted string prints the literal text $city because single quotes do not interpolate variables. The double-quoted string replaces $city with its value. This is the key difference to remember when you decide which quote style to use.
Escape sequences
Inside double-quoted strings you can use escape sequences — a backslash followed by a character — to represent things that are hard to type directly. These let you include newlines, tabs, and literal quote marks without breaking the string.
Using escape sequences
<?php
echo "Line one\nLine two";
echo "\n";
echo "She said \"hello\" to me";
echo "\n";
echo "Cost: \$50";
?>String length and accessing characters
You can measure how many characters a string contains with strlen(), and you can reach an individual character by its position using square brackets. Positions are zero-based, so the first character is at index 0. This makes it easy to loop over a string or inspect specific characters.
Length and character access
<?php
$word = "planet";
echo strlen($word); // 6
echo "\n";
echo $word[0]; // p
echo "\n";
echo $word[5]; // t
?>Exercise: PHP Strings
Which operator joins two strings together in PHP?