Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string concatenation using ","?

I just discovered something.

echo $var1 , " and " , $var2;

is the same as:

echo $var1 . " and " . $var2;

What is the actual string concatenation operator in php? Should I be using . or ,?

like image 635
bbtang Avatar asked Nov 28 '22 19:11

bbtang


2 Answers

The . operator is the concatenation operator. Your first example only works because the echo 'function' (technically it's a language construct, but lets not split hairs) accepts more than one parameter, and will print each one.

So your first example is calling echo with more than one parameter, and they are all being printed, vs. the second example where all the strings are being concatentated and that one big string is being printed.

like image 83
Matthew Scharley Avatar answered Nov 30 '22 07:11

Matthew Scharley


The actual concatenation is . (period). Using , (comma) there, you are passing multiple arguments to the echo function. (Actually, echo is not a function but a PHP language construct, which means you can omit the parentheses around the argument list that are required for actual function calls.)

like image 30
Greg Hewgill Avatar answered Nov 30 '22 09:11

Greg Hewgill