Strings

PHP gives you two ways to write a string literal, a dedicated operator for gluing strings together, and a large standard library of string functions — some of the oldest and most-used code in the language.

Single quotes versus double quotes

Single-quoted strings are taken almost literally. Double-quoted strings interpolate variables and interpret escape sequences like \n:

PHP quotes.php
<?php
$name = "Sam";

echo 'Hello, $name\n';
echo "Hello, $name\n";
?>
Output
Hello, $name\n
Hello, Sam

The single-quoted line prints $name and \n completely literally — no substitution, no newline, just the raw characters. The double-quoted line replaces $name with its value and turns \n into an actual line break. Single quotes are the better default for plain text with no variables in it, since there's nothing for PHP to scan for.

Concatenation with the dot operator

PHP uses . to join strings together, and .= to append onto an existing variable:

PHP concat.php
<?php
$first = "Ada";
$last = "Lovelace";
$full = $first . " " . $last;

echo $full . "\n";

$message = "Hello";
$message .= ", " . $full;
$message .= "!";

echo $message;
?>
Output
Ada Lovelace
Hello, Ada Lovelace!
Note: PHP uses . for string concatenation and + strictly for arithmetic — the two are never interchangeable the way + is overloaded for both in JavaScript. Writing $first + $last here would try to convert both strings to numbers (getting 0 for each) and add those.

Common string functions

PHP's string function library is large and mostly flat (not method calls on the string itself) — strlen(), strtoupper()/strtolower(), str_replace(), and substr() cover a large share of everyday needs:

PHP functions.php
<?php
$text = "Hello, PHP World";

echo strlen($text) . "\n";
echo strtoupper($text) . "\n";
echo strtolower($text) . "\n";
echo str_replace("World", "Learner", $text) . "\n";
echo substr($text, 7, 3) . "\n";
?>
Output
16
HELLO, PHP WORLD
hello, php world
Hello, PHP Learner
PHP

substr($text, 7, 3) starts at index 7 (0-based, so the P in PHP) and takes 3 characters. Like most PHP string functions, the string you're working on is passed in as the first argument rather than called as a method — strlen($text), not $text.length().

Building strings with sprintf

When a string needs several values slotted into a fixed template, sprintf() is often clearer than a long chain of concatenation:

PHP sprintf.php
<?php
$name = "Maya";
$score = 87.5;

$line = sprintf("%s scored %.1f%%", $name, $score);
echo $line;
?>
Output
Maya scored 87.5%

%s substitutes a string, %.1f substitutes a float rounded to one decimal place, and %% is how you get a literal percent sign since a lone % would otherwise start a new format specifier.