String Operators
PHP has exactly two operators dedicated to strings: the concatenation operator ., which joins strings together, and the concatenation-assignment operator .=, which appends to an existing string variable. That is the entire family — but it is worth a full page because the most common mistake people bring from other languages involves this exact pair.
Concatenation with .
The . operator takes two operands, converts each to a string if it is not one already, and glues them together into a new string. It works between two strings, a string and a number, or any combination that can be converted to text.
Concatenation
<?php $firstName = "Ada"; $lastName = "Lovelace"; $fullName = $firstName . " " . $lastName; echo $fullName; // Ada Lovelace $age = 36; echo "Age: " . $age . " years"; // Age: 36 years - number converted to string
Ada Lovelace Age: 36 years
Appending with .=
.= is shorthand for "take the current string, concatenate something onto the end, and store the result back in the same variable." It shows up constantly when building up a string piece by piece, such as inside a loop.
Building a string with .=
<?php
$html = "<ul>";
foreach (["Milk", "Eggs", "Bread"] as $item) {
$html .= "<li>{$item}</li>";
}
$html .= "</ul>";
echo $html;<ul><li>Milk</li><li>Eggs</li><li>Bread</li></ul>
Why not just use +?
Many languages (JavaScript included) overload + to mean both numeric addition and string concatenation depending on the operand types. PHP deliberately does not do this. + in PHP always means numeric addition, even when both operands look like strings.
Numeric strings with +
<?php $a = "10"; $b = "20"; echo $a + $b; // 30 - both converted to numbers and added echo "\n"; echo $a . $b; // "1020" - concatenated as text
30 1020
What actually happens with non-numeric strings and +
<?php
try {
$result = "Hello " + "World";
} catch (\TypeError $e) {
echo "Caught: " . $e->getMessage();
}Caught: Unsupported operand types: string + string
Interpolation as an alternative to concatenation
For simple cases, double-quoted string interpolation (covered on the Variables page) often reads more cleanly than a chain of . operators, especially once you have more than two or three pieces to join.
Concatenation vs interpolation
<?php
$name = "Marco";
$score = 95;
// Concatenation
echo $name . " scored " . $score . " points.";
echo "\n";
// Interpolation - usually easier to read
echo "{$name} scored {$score} points.";Marco scored 95 points. Marco scored 95 points.
.concatenates any two values, converting non-strings to strings first..=appends to an existing string variable — ideal for building output in a loop.+is always numeric addition in PHP, never concatenation.Interpolation (
"{$var}") is often clearer than.for a handful of variables mixed with text.