PHP use string as operator
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
}
The easiest but most dangerous method is to use eval
.
$c = eval("return $a $char $b;");
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...
}
}