PHP Strings Introduction
In this page:
Single Quoted Strings
Single-quoted strings do the least amount of work: they don't evaluate $variable references or process most escape sequences, printing almost everything exactly as typed. That simplicity makes them marginally faster and the right choice for plain, static text.
Example: Single Quoted Strings
<?php
$name = "Alice";
echo 'Hello, $name';
?>
Login to try C/C++/Java/PHP code in the editor
Double Quoted Strings
Double-quoted strings actively process their contents: any $variable inside is replaced with its current value (interpolation), and escape sequences like \n and \t are converted into a real newline or tab rather than printed as literal backslash-n.
Example: Double Quoted Strings
<?php
$name = "Alice";
echo "Hello, $name\n";
?>
Login to try C/C++/Java/PHP code in the editor
String Concatenation
The . operator joins two strings end-to-end into one — $greeting = 'Hello, ' . $name; — and .= does the same thing while also reassigning the result back into the left-hand variable, appending onto whatever it already contained.
Example: String Concatenation
<?php
$name = "Alice";
$greeting = 'Hello, ' . $name;
echo $greeting;
?>
Login to try C/C++/Java/PHP code in the editor
Checking String Length
strlen() returns the total number of bytes in a string, counting every character including spaces and punctuation. For strings containing multi-byte characters (accented letters, emoji), strlen() counts bytes rather than visible characters, which is worth knowing before you rely on it for display-length logic.
Example: Checking String Length
<?php
$text = "Hello!";
echo strlen($text);
?>
Login to try C/C++/Java/PHP code in the editor
Accessing Single Characters
You can read (or overwrite) a single character in a string using square-bracket indexing, exactly like an array — $word[0] gets the first character. PHP strings are zero-indexed, so the first character sits at position 0, not 1.
Example: Accessing Single Characters
<?php
$word = "Hello";
echo $word[0];
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: