PHP String Concatenation
Concatenation is the process of joining two or more strings together to build a single larger string.
The concatenation operator
In PHP you join strings together using the dot operator, written as a single period between two values. This is different from many other languages that reuse the plus sign for both addition and string joining. Keeping a separate operator means PHP never has to guess whether you want to add numbers or glue text, which removes a common source of confusion.
Joining strings with the dot operator
<?php
$firstName = "Grace";
$lastName = "Hopper";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Grace Hopper
?>Notice the middle piece, a string containing a single space. Without it the two names would run together as GraceHopper, because concatenation joins values exactly as they are with nothing added in between.
The concatenating assignment operator
When you want to keep adding to an existing string, PHP offers a shorthand: the .= operator. It appends the value on its right to the variable on its left. This is especially handy when building a string piece by piece inside a loop, where you accumulate text over several iterations.
Building a string step by step
<?php
$list = "";
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
$list .= "- " . $fruit . "\n";
}
echo $list;
// - apple
// - banana
// - cherry
?>Concatenation versus interpolation
Concatenation is not the only way to combine text and variables. Inside a double-quoted string you can drop a variable directly into the text, a technique called interpolation. Both approaches produce the same result, so the choice often comes down to readability. Interpolation tends to read more cleanly when you have a few variables mixed into fixed text, while concatenation is clearer when you are joining the results of expressions or function calls.
- Concatenation: joins separate pieces with the dot operator, giving you fine control.
- Interpolation: embeds variables inside a double-quoted string for compact, readable text.
- For complex expressions inside interpolation, wrap them in curly braces like {$user->name}.
Two ways to reach the same result
<?php
$product = "laptop";
$price = 999;
// Using concatenation
echo "The " . $product . " costs $" . $price;
echo "\n";
// Using interpolation
echo "The $product costs \$$price";
?>