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

Here is a 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 only gives a value like this

 6 2 8 2 

If I put (instead of a comma). (dot) then it gives the correct conclusion similar to this

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

Why is this happening?

+6
source share
2 answers

This is due to php operator precedence ...

An expression containing . , is executed before expressions containing + , so the implicit parentheses are as follows:

.+- are equal operators (they have no priority), and they are executed sequentially from beginning to end, so the implicit brackets are as follows:

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

So, if you want to get the correct result, you should use:

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

Empirical examples:

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

And why it works ... Since coma separates the arguments of the function, and php sees this as:

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

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

+3
source

The difference is that it , not a concatenation operator, but it allows you to start from the beginning

 echo "$a+$b=". $a+$b; 

with $a=2 and $b=4 is evaluated as

 echo ("4+2=". 4)+2; echo "4+2=4"+2; echo ((int) "4+2=4")+2; echo 4+2; echo 6 

The fact is that the comma , not combined, but it lists the expressions (at least for echo . The manual just says "uses a lot" ...), so each expression is executed by itself.

 echo "$a+$b=", $a+$b; echo "$a+$b="; echo $a+$b; echo "2+4=";echo 2+4; 
0
source

Source: https://habr.com/ru/post/908067/


All Articles