Alex
Alex

Reputation: 68472

PHP - arithmetic operations using strings as operators

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

Answers (4)

John Gardner
John Gardner

Reputation: 25126

trickery with math:

echo $initial + (($operation == '-') ? -1 : 1) * $unit;

only using addition, but cheating with multiplying by a negative... :)

Upvotes: 3

Mark Baker
Mark Baker

Reputation: 212412

echo ($operation == '+') ? $initial + $unit : $initial - $unit;

Upvotes: 1

Alin P.
Alin P.

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

Jeff Hubbard
Jeff Hubbard

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

Related Questions