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?
Comma is a separator between parameters in the parameter list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With