Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between , (comma) and . (dot) as a concatenation operator?

Tags:

php

Here is simple PHP code

echo '<form method="POST" action="calcbyme.php"></br>
    enter value1 :<input type="text" name="f1"></br>
    give operator :<input type="text" name="op"></br>
    enter value2 :<input type="text" name="f2"></br>
    <input type="submit" value="calculate"></br>';
    if(isset( $_POST["f1"]) && isset($_POST["f2"]) && isset($_POST["op"]) ){
        $a=$_POST["f1"];
        $b=$_POST["f2"];
        $op=$_POST["op"];
        switch ($op){
            case '+':
                echo "$a+$b=". $a+$b; break;
            case '-':
                echo  "$a-$b=". $a-$b; break;
            case '*':
                echo "$a*$b=". $a*$b; break;
            case '/';
                echo "$a/$b=". $a/$b; break;
            default:
                echo "invalid operator"; break;
        }
    }

If I assume $a=4 and $b=2 but this give only value like this

6
2
8
2

If I put , (comma) instead of . (dot) then it gives correct output like this

4+2=6
4-2=2
4*2=8
4/2=2

Why does this happen?

like image 471
Rahul Virpara Avatar asked Feb 09 '12 17:02

Rahul Virpara


People also ask

What does a comma do in PHP?

Comma is a separator between parameters in the parameter list.


1 Answers

It has to do with php operator precedence...

Expression containing . is executed before expressions containing +, therefor implicit brackets are:

.+- are equal operators (there's no precedence applied on them) and they are executed sequentially from start to end, therefor implicit brackets are:

echo ("$a+$b=". $a)+$b

So if you want correct output you should use:

echo "$a+$b=". ($a+$b)

Empiric examples:

php > echo "foo" . 1 + 2;
// 2
php > echo "foo" . (1 + 2);
// foo3
php > echo 1 + 3 . 'foo';
// 4foo

And why is , working... Because coma separates function arguments and php sees this as:

echo( "$a+$b=", $a+$b);

And coma operator (,) is evaluated as last one.

like image 162
Vyktor Avatar answered Nov 02 '22 00:11

Vyktor