Reputation: 49
I am making very simple program in PHP . Tryig to addition first ..
But dont know ..
Here is code
<?php
$a=12;
$b=10;
$c="+";
$res=$a."$c".$b;
echo $res;
?>
it output 12+10 as it is concecate..
$c is anything.
Any idea how to do this
Upvotes: 0
Views: 150
Reputation: 109547
Yes, also PHP has an eval(uate)
function:
$res = eval($a . $c . $b);
Be sure that $a, $b and $c do not stem from form input, as eval can delete and so on.
Upvotes: 0
Reputation: 29424
What do you want to do exactly?
If you have the operator as a string, you could try a switch
statement:
<?php
$a=12;
$b=10;
$c="+";
switch($c) {
case '+':
$res = $a + $b;
break;
case '-':
$res = $a - $b;
break;
}
var_dump($res);
?>
Upvotes: 2
Reputation: 3014
$c is now a string and not a expression "+" is not equal to +.
So:
$res=$a + $b;
If you would really need your structure you would have to do something evil like using eval() or you could do:
$a=12;
$b=10;
$operator='+';
switch($operator) {
case '+':
$res=$a + $b;
break;
case '-':
$res=$a - $b;
break;
}
Upvotes: 5