Difference between period and comma when concatenating with echo versus return?
Dot (.
) is for concatenation of a variable or string. This is why it works when you echo while concatenating two strings, and it works when you return a concatenation of a string in a method. But the comma doesn't concatenate and this is why the return statement won't work.
echo
is a language construct that can take multiple expressions which is why the comma works:
void echo ( string $arg1 [, string $... ] )
Use the dot for concatenation.
You also have to note that echo
as a construct is faster with commas than it is with dots.
So if you join a character 4 million times this is what you get:
echo $str1, $str2, $str3;
About 2.08 seconds
echo $str1 . $str2 . $str3;
About 3.48 seconds
It almost takes half the time as you can see above.
This is because PHP with dots joins the string first and then outputs them, while with commas just prints them out one after the other.
We are talking about fractions of a second, but still.
Original Source
return
only allows one expression, but echo
allows a list of expressions where each expression is separated by a comma.
But note that since echo
is not a function but a special language construct, wrapping the expression list in parenthesis is illegal.
The .
is the concatenation operator in PHP, for putting two strings together.
The comma can be used for multiple inputs to echo
.