PHP implements the stack-based suffix expression evaluate function, and php suffix expression evaluate
This example describes how to evaluate a stack-based suffix expression in PHP. We will share this with you for your reference. The details are as follows:
Suffix expression Overview
Suffix expression, which does not contain parentheses. Operators are placed behind two calculation objects. All calculation operations are performed in the order in which operators appear, strictly go from left to right (the priority rules of operators are not considered ).
Implementation Code:
<?phpclass Stack{ public $stack; public $stack_top; public function __construct(){ $this->stack=array(); $this->stack_top=-1; } public function push($data){ $this->stack[]=$data; $this->stack_top++; } public function pop(){ if(!$this->is_empty()) { $this->stack_top--; return array_pop($this->stack); }else { echo "stack is empty"; } } public function is_empty(){ if($this->stack_top==-1) return true; }}$string="1243-*+63/-";$arrs=str_split($string);echo var_export($arrs);$stack=new Stack();foreach($arrs as $arr){ switch($arr){ case "+":$one=$stack->pop();$two=$stack->pop();$temp=$two + $one;$stack->push($temp);break; case "-":$one=$stack->pop();$two=$stack->pop();$temp=$two - $one;$stack->push($temp);break; case "*":$one=$stack->pop();$two=$stack->pop();$temp=$two * $one;$stack->push($temp);break; case "/":$one=$stack->pop();$two=$stack->pop();$temp=$two / $one;$stack->push($temp);break; default:$stack->push($arr); }}echo $stack->pop();?>
Running result:
array ( 0 => '1', 1 => '2', 2 => '4', 3 => '3', 4 => '-', 5 => '*', 6 => '+', 7 => '6', 8 => '3', 9 => '/', 10 => '-',)1