0

What are the differences in the results of these three strings:

  1. echo "Hello" . "World! <br />";

  2. echo "Hello"; echo "World!" , "<br />";

  3. echo "Hello" , "World!" , "<br />";

Is there any preferred way to concatenate strings or are they all acceptable?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Alex
  • 627
  • 3
  • 12
  • 32
  • 2. is no concatenation and since I'm unfimiliar with `,` I'm gonna go and say it is equivalent to `.`. – kero May 09 '14 at 14:36
  • @kingkero It's not. :) – deceze May 09 '14 at 14:37
  • @kingkero it might not be concatenation but is there a different on the output? Is there a reason that you would prefer to do it another way? – Alex May 09 '14 at 14:37
  • 4
    The period (`.`) is the actual concatenation operator. The comma (`,`) is just passing multiple arguments to `echo` function (before someone corrects me, I know it is a language construct). – Amal Murali May 09 '14 at 14:37
  • The comma is the fastest regarding performance – Дамян Станчев May 09 '14 at 14:38
  • possible duplicate of [Reference: Comparing PHP's print and echo](http://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo) – deceze May 09 '14 at 14:38
  • 3
    @ДамянСтанчев: In the real world, the difference between these two would be infinitesimal that you'd need at least a few thousand iterations to even know there's a performance difference. It's micro-optimization at best. – Amal Murali May 09 '14 at 14:42

2 Answers2

1

The preferred way is to use the dot.

Most php programmers don't even know it is possible to use the comma. Having two echo statements is less readable, and slightly less performant.

winkbrace
  • 2,682
  • 26
  • 19
  • It is also preferred to use 'single quotes' for simple strings. Using double quotes evokes a small processing engine that parses the string looking for variable names and escape characters. – efreed May 09 '14 at 16:00
  • that makes so little difference it should never be a factor. – winkbrace May 09 '14 at 21:25
1

The concatenation operator is '.', the comma doesn't concatenate. In the examples you made, only the first one is concatenation.

On the other side, the echo construct, accepts many parameters which are separated by commas.

Kei
  • 771
  • 6
  • 17