Reputation: 301
How can I make php to see this variable like a -
or +
:
example:
$operation = '+';
$sum = $val1 $operation $val2 // I want to make $val1 + $val2;
but I get an error that the $operation variable is unexpected, how to realize this?
Upvotes: 1
Views: 47
Reputation: 26719
You can use variable function instead
$functions = array(
'+' => 'plus',
'-' => 'minus',
'*' => 'multiply'
);
if (isset($functions[ $operation ]) {
$operation = $functions[ $operation ];
$result = $operation($val1, $val2);
}
Upvotes: 0
Reputation: 324750
While you could take the "lazy" way and do:
$sum = eval('return $val1 '.$operation.' $val2;');
It would be safer to use a switch
:
switch($operation) {
case "+": $sum = $val1 + $val2; break;
case "-": $sum = $val1 - $val2; break;
// define more operations here
default: throw new Exception("Unrecognised operation ".$operation);
}
Upvotes: 6