String concatenation with echo

suggest change

You 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;

The problem with the concatenation is that the period . takes precedence in the expression. If concatenated, the above expression needs extra parentheses for the correct behavior. The precedence of the period affects ternary operators too.

echo "The total is: " . ($x + $y);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents