Home >Backend Development >PHP Tutorial >PHP tutorial: PHP implements stack-based suffix expression evaluation function
What is a suffix expression? Postfix expression means that it does not contain parentheses, and the operator is placed after the two operands. All calculations are performed strictly from left to right in the order in which the operators appear (the precedence rules of operators are no longer considered). This PHP tutorial mainly uses examples to describe the stack-based suffix expression evaluation function in PHP. Share it with everyone for your reference, the details are as follows:
Implementation code:
<?php class 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
After studying this article, everyone must have some understanding of postfix expressions, and also learned how to use PHP to implement stack-based postfix expressions Evaluation function, this method is very useful for programmers. More related content will be introduced later to encourage everyone.
I hope this article will be helpful to everyone in PHP programming.
Related recommendations:
3 recommended articles about suffix expressions
php four arithmetic operations: converting infix expressions to suffix expressions Formula example
Convert four arithmetic expressions into postfix expressions
The above is the detailed content of PHP tutorial: PHP implements stack-based suffix expression evaluation function. For more information, please follow other related articles on the PHP Chinese website!