Comma as a concatenation operator in php

In php we can output strings in different ways as we can use echo or print to display output text.

Difference between echo and print:

echo and print are not functions but language constructs. Both are used to output strings.
echo can take multiple parameters but print can take only one parameter.
echo does not return any value whereas print always return 1 (integer)

In php concatenation can be possible by using two operators dat(.) and comma (,) symbols.

Concatenate string with dot(.) operator:-

a) Dot can be used for just concatenate left and right arguments as below

$str1 = "Foo ";
$str2 = $str1 . "Bar";
echo $str2;

Output:-

Foo Bar

b) Dot can we used as a assignment operator

$str = "Foo ";
$str .= "Bar";

print $str;

Output:-

Foo Bar

Concatenate string with comma(,) :-

We can use Comma as a concatenation operator in php to multiple parameters

echo 'Multiple Parameter ', 'Example With ', ' echo.';
// Output: Multiple Parameter Example With echo.

print 'Multiple Parameter ', 'Example With ', ' print.';
//Parse error: syntax error, unexpected ',' in <filename>.php

Test performance of echo and print with different concatenation operators:

To test performance I have written script which will join this string 1000 times. and output the time in seconds taken in concatenation.

Benchmark Script:-

<?php
$str1 = str_repeat('a', 100);
$str2 = str_repeat('b', 100);
$str3 = str_repeat('c', 100);

$startTime = microtime(true);

for($i = 0; $i < 1000; $i++) {
    ob_start();
    for($j = 0; $j < 1000; $j++) {
    echo $str1 , $str2 , $str3; // replace with other combinations :)
}
  ob_get_clean();
}
echo microtime(true) - $startTime;
?>

1) Print with dot – 67438912391663 seconds.

print $str1 . $str2 . $str3;

2) echo with dot – 0.67276191711426 seconds

echo $str1 . $str2 . $str3;

3) echo with comma – 0.57042098045349 seconds

echo $str1 , $str2 , $str3;

Conclusion:- echo with comma has fastest result.

(Visited 1,248 times, 59 visits today)