Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
604 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...