String concatenation with echo
suggest changeYou can use concatenation to join strings “end to end” while outputting them (with echo or print for example).
You can concatenate variables using a . (period/dot).
// String variable
$name = 'Joel';
// Concatenate multiple strings (3 in this example) into one and echo it once done.
// 1. ↓ 2. ↓ 3. ↓ - Three Individual string items
echo '<p>Hello ' . $name . ', Nice to see you.</p>';
// ↑ ↑ - Concatenation Operators
#> "<p>Hello Joel, Nice to see you.</p>"
Similar to concatenation, echo (when used without parentheses) can be used to combine strings and variables together (along with other arbitrary expressions) using a comma (,).
$itemCount = 1;
echo 'You have ordered ', $itemCount, ' item', $itemCount === 1 ? '' : 's';
// ↑ ↑ ↑ - Note the commas
#> "You have ordered 1 item"
String concatenation vs passing multiple arguments to echo
Passing multiple arguments to the echo command is more advantageous than string concatenation in some circumstances. The arguments are written to the output in the same order as they are passed in.
echo "The total is: ", $x + $y;
Before PHP 8, . and + had the same precedence and associated left to right, so "The total is: " . $x + $y was ("The total is: " . $x) + $y. Since PHP 8, + and - bind more tightly than ., and that expression already adds first. Parentheses still make the intent obvious. . also binds more tightly than ?:, so "a" . $cond ? "b" : "c" is ("a" . $cond) ? "b" : "c".
echo "The total is: " . ($x + $y);