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:


Outputting the value of a variable:
* String concatenation with echo

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
84 Outputting the value of a variable
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR