PHP Concatenation – Comma (,) vs Dot (.)

While on a chat with a friend who recently started learning PHP programming language, he ask me what is the difference between using a comma (,) and a dot (.) as a concatenator.

My answer to him was: for the record, comma isn’t a concatenator. it use for printing or rather echoing a list of variable, string and numbers similar to how it is used in English. While dot joins two strings together to make one longer string.

Take note: comma only work when using the echo language construct and you can’t return a comma delimited variable.

Examples

Let’s see some code example.

  • 
    <?php
    $a = 'i am';
    $b = ' boy';
    echo $a, $b;
    
    
    <?php
    $a = 'i am';
    $b = ' boy';
    $c = $a . $b;
    echo $c;
    
    
    <?php
    $a = 'i am';
    $b = ' boy';
    echo $a . $b;
    

    Result: i am boy

  • 
    <?php
    $a = 'i am';
    $b = ' boy';
    print($a, $b);
    
    
    <?php
    $a = 'i am';
    $b = ' boy';
    $c = $a, $b;
    
    
    <?php
    $a = 'i am';
    $b = ' boy';
    return $a , $b;
    

    Result: Parse error: syntax error, unexpected ‘,’ in C:\xampp\htdocs\index.php on line 4

It is worth noting that when using echo, delimiting string with comma is faster than dot.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address