0

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?

bzlm
  • 9,626
  • 6
  • 65
  • 92
Mike Johnson
  • 351
  • 2
  • 8

6 Answers6

11

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
  • 96,375
  • 17
  • 202
  • 225
3

No, you cannot concatenate with comma:

<?php

$foo = 'One', 'Two';

?>

Parse error: syntax error, unexpected ','

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
1

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
  • 83,810
  • 28
  • 209
  • 234
1

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
  • 12,790
  • 2
  • 41
  • 42
1

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.

Community
  • 1
  • 1
rmartinez
  • 81
  • 1
  • 6
-1
echo('hello', ' world');

It's the same as:

echo 'hello', ' world';
Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
Centurion
  • 5,169
  • 6
  • 28
  • 47