Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP use string as operator

Say I have a string, $char. $char == "*".

I also have two variables, $a and $b, which equal "4" and "5" respectively.

How do I get the result of $a $char $b, ie 4 * 5 ?

Thanks :)

like image 901
Fela Maslen Avatar asked Apr 25 '11 16:04

Fela Maslen


2 Answers

You can use eval() as suggested by @konforce, however the safest route would be something like:

$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){

  case "*":
    $result = $left * $right;
    break;

 case "+";
   $result = $left + $right;
   break;
// etc

}
like image 159
Mike Lewis Avatar answered Nov 14 '22 07:11

Mike Lewis


safest method is a switch construct:

function my_operator($a, $b, $char) {
    switch($char) {
        case '=': return $a = $b;
        case '*': return $a * $b;
        case '+': return $a + $b;
        etc...
    }
}
like image 10
Marc B Avatar answered Nov 14 '22 09:11

Marc B