Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP's echo, when does the difference between . and , matter?

Tags:

syntax

php

I noticed recently that there are two ways to print multiple statements in PHP.

echo $a.$b; // Echo's $a and $b conjoined, and
echo $a,$b; // Echo's $a and echo's $b.

Is there any point in time where the difference between these two syntaxes matters?

like image 952
Navarr Avatar asked Dec 04 '22 12:12

Navarr


2 Answers

Realistically, no.

echo $a.$b first concatenates $a and $b into a new string, then passes it as a parameter to echo, which prints it out.

echo $a,$b gives two parameters to echo, which will print both out.

The latter is slightly more efficient. Not in any way that you would normally notice though.

There is a difference in how it is evaluated. echo $a, $b is like writing echo $a; echo $b;, two separate calls. $b will be evaluated after $a is echo'd. This can make a difference if your arguments are function calls which themselves echo something, but again, in practice this should be irrelevant, since it's bad practice.

like image 133
deceze Avatar answered Feb 15 '23 23:02

deceze


There is a difference that is good to note. With the second synthax, the first parameter will still output even if the second one causes an error.

<?php
echo 1, error(); // This outputs 1, then it displays an error 
?>

While the first one won't echo the first part.

<?php
echo '1' . error(); // Only displays an error
?>

When you separate your parameter with a comma, it will echo them one after the other. When you use the dot operator, it will concatenate them into a string and then it will echo it.

like image 27
HoLyVieR Avatar answered Feb 15 '23 23:02

HoLyVieR