user3414354
user3414354

Reputation: 301

php how to make php parse - and + signs

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

Answers (2)

Maxim Krizhanovsky
Maxim Krizhanovsky

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions