Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function rpn($expr){
- if(is_string($expr)){
- $expr = explode(" ", $expr);
- }
- $stack = [];
- foreach($expr as $e){
- if(is_numeric($e)){
- $stack[] = $e;
- } else {
- $n1 = array_pop($stack);
- $n2 = array_pop($stack);
- $result = null;
- if($e == "+"){
- $result = $n2 + $n1;
- } elseif($e == "*"){
- $result = $n2 * $n1;
- } elseif($e == "-"){
- $result = $n2 - $n1;
- } elseif($e == "/"){
- $result = $n2 / $n1;
- }
- array_push($stack, $result);
- }
- }
- if(count($stack) != 1){
- throw new TypeError("Invalid rpn expression");
- }
- return array_pop($stack);
- }
Add Comment
Please, Sign In to add comment