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?
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:So if you want correct output you should use:
Empiric examples:
And why is
,working… Because coma separates function arguments and php sees this as:And coma operator (
,) is evaluated as last one.