PHP has only two string operators. They both join strings, which is called concatenation.
| Operator | Name | Example |
|---|---|---|
. | Concatenation | "Hello" . " world" |
.= | Concatenation assignment | $text .= " more" |
<?php
$first = "Ada";
$last = "Lovelace";
$full = $first . " " . $last;
echo $full;
Ada Lovelace
Adding to a string
<?php
$message = "Order placed.";
$message .= " We will email you.";
$message .= " Thank you!";
echo $message;
Order placed. We will email you. Thank you!
Numbers become text
When you join a number with a string, PHP converts the number to text for you.
<?php
$items = 3;
echo "You have " . $items . " items.";
You have 3 items.
A dot next to a number
Be careful with spaces around a dot and a number. 1 . 2 and 1.2 are different things.
<?php
echo 1 . 2 . "\n"; // concatenation: "12"
echo 1.2 . "\n"; // the number 1.2
12
1.2
Mixing + and .
In PHP 8, + is calculated before .. In older versions, they had the same priority, which gave confusing results. Brackets make it clear in any version.
<?php
echo "Total: " . (2 + 3);
Total: 5
Or use interpolation
For short text, putting variables inside double quotes is often neater than many dots. See String Interpolation.
<?php
$name = "Ada";
$age = 36;
echo "Name: " . $name . ", age: " . $age . "\n";
echo "Name: $name, age: $age";
Name: Ada, age: 36
Name: Ada, age: 36
Using + to join strings
"a" + "b" joins. In PHP, + is only for numbers, and "a" + "b" throws an error. Use the dot.