Reputation: 68472
I have a string variable, $operation
, that can have values like +
or -
and two integer variables $initial
and $unit
.
So to echo the result of the arithmetic operation between them
I have to use something like
if($operation == '+') echo ($initial + $unit);
if($operation == '-') echo ($initial - $unit);
Is there a way I can do this without the IF?
Upvotes: 1
Views: 5117
Reputation: 25126
trickery with math:
echo $initial + (($operation == '-') ? -1 : 1) * $unit;
only using addition, but cheating with multiplying by a negative... :)
Upvotes: 3
Reputation: 212412
echo ($operation == '+') ? $initial + $unit : $initial - $unit;
Upvotes: 1
Reputation: 44346
With eval.
But make sure you do your whitelist validations before feeding anything to eval
.
if(in_array($operation, array('+', '-'))){
eval('echo $initial '.$operation.' $unit;');
}
Upvotes: 0
Reputation: 9892
You could use a map, i.e.
function add($a, $b) { return $a + $b; }
function sub($a, $b) { return $a - $b; }
$operations = array('+' => 'add', '-' => 'sub');
$operations[$operation]($initial, $unit);
Upvotes: 3