PHP Reference ยท Operators
PHP string operators
Reference for PHP string operators: the dot concatenation operator and .=, how numbers convert, precedence changes in PHP 8 and faster alternatives.
PHP has two string operators. The concatenation operator . joins two values into one string, and the concatenating assignment .= appends to a variable. Operands that are not strings are converted first: integers and floats become their decimal text, true becomes "1", false and null become "".
The dot is also what separates PHP from +: + always does arithmetic, so "1" + "2" is 3 while "1" . "2" is "12".
$greeting = "Hello, " . $name . "!"; $log .= "line\n";
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$result = $a . $b; $variable .= $value;
| Operator | Meaning |
|---|---|
. |
Concatenate the string forms of the operands |
.= |
$a = $a . $b |
Return value: a new string.
Errors: an array operand gives a warning ("Array to string conversion") and the text Array. An object without __toString() throws Error.
Usage notes
- Precedence changed in PHP 8.
+and-now bind tighter than., so"Price: " . $price + 1adds first. In PHP 7 the dot came first. Use parentheses when mixing them. - Interpolation (
"Hello $name","{$user->name}") is usually more readable than a chain of dots. - Many pieces. For long strings use
implode(),sprintf()or output buffering. Appending with.=in a loop is fine; PHP strings are efficient to extend. - Output.
echo $a, $bwith commas avoids building a temporary string and is a hair faster thanecho $a . $b. - Numbers. Floats print using the
precisionsetting; usenumber_format()orsprintf()for fixed decimals. - Dot next to numbers.
1 . 2needs spaces:1.2is a float. - Multibyte.
.works on bytes and is safe for UTF-8 text because it only joins.