views:

142

answers:

7

Hi,

I know that to concatenate strings in php, a dot should be used:

echo 'hello' . ' world'; // hello world

But incidentally i typed this:

echo 'hello' , ' world';

and the result was still hello world without any errors.

Why is it so? Can we also concatenate using comma?

+11  A: 

It's documented in the entry for echo:

void echo ( string $arg1 [, string $... ] )

The two forms are not actually equivalent, since there's a difference in the instant in which functions are evaluated.

Artefacto
Darn beat me to it...
NullUserException
+1  A: 

echo is a language construct, so you don't need parenthesis. But you are "passing" multiple parameters to echo. Think of it as:

echo('hello', ' world');

NullUserException
Special construct? :)
bzlm
@bzim language construct. At least I didn't say it "flattened the array" ;)
NullUserException
@Null But that's exactly what it did. :)
bzlm
+1  A: 

It's no hidden trick, it's just how echo works. If you have a look at the PHP reference docs for echo, you'll notice that it will echo the list of strings that you throw at it.

wimvds
A: 

Maybe it is because echo statement is special? It is not concatenation, you just give multiple parameters to echo.

BlaXpirit
+2  A: 

No, you cannot concatenate with comma:

<?php

$foo = 'One', 'Two';

?>

Parse error: syntax error, unexpected ','

Álvaro G. Vicario
Excellent answer.
Col. Shrapnel
A: 

echo('hello', ' world'); it the same as: echo 'hello', ' world';

Centurion
A: 

echo is a language construct. It is in someway a special function that's defined at Grammar level (I might be wrong on this). It is a function that somehow doesn't follow any of the defined way of defining a function/method as an example and the way of calling them. It "by-passes" some syntax check :)

There's a nice post discussing the difference between language construct & built in functions here in StackOverflow.

rmartinez