views:

157

answers:

8

I just discovered something. If I type this:

echo $var1 , " and " , $var2;

it is the same as:

echo $var1 . " and " . $var2;

What is the actual of concatenation operator in php? Using . or ,?

+2  A: 

".". The other just writes several values independently, without actually concatenating the string.
See also PHP echo reference, the "," variant will only work with methods accepting multiple parameters.

Lucero
+2  A: 

"." concatenates, "," can only be used for echo which is a language construct (sort of a function)

also see: http://stackoverflow.com/questions/1466408/difference-between-and-in-php

knittl
+3  A: 

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.)

Greg Hewgill
+2  A: 

In the first case you just echo 3 different strings.

In the second case you concatenate the 3 strings and then echo the output.

So the answer is that, in order to concatenate strings you should use the dot (.)

Anax
A: 

nop it's because echo could take more then one argument, it would do the print each arguments

RageZ
I doubt echo does a concatentation, it just prints each parameter.
Matthew Scharley
yeah but happens to have the same effect.
RageZ
+8  A: 

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.

Matthew Scharley
One more note. `echo` does not take multiple arguments if you call it using parens. This won't work: `echo($a, $b);`
Ionuț G. Stan
I read somewhere that echo "a", "b"; is faster than echo "a"."b";
Kamil Szot
I doubt it's noticably faster, except perhaps for very large 'a' and 'b'. I do believe it though.
Matthew Scharley
+1  A: 

Using a comma doesn't actually concatenate the strings.

See this answer to another question.

kkyy
+1  A: 

The "." is the correct concatenate operator. "echo" also accepts ",", treating it as if you are passing in a series of arguments to the "echo" method and then echoing each one. It's not truly concatenating the strings.

Mike A.