Created
October 10, 2025 18:52
-
-
Save D1360-64RC14/c147a9d88305fc6885c212fb83c5edcd to your computer and use it in GitHub Desktop.
A Reverse Polish Notation expression calculator in PHP 8.4 using BCMath.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function bc(string $exp): string | |
| { | |
| $stack = []; | |
| $tokens = explode(' ', $exp); | |
| foreach ($tokens as $token) { | |
| if (strlen($token) <= 0) continue; | |
| switch ($token) { | |
| case '+': | |
| while (($c = count($stack)) > 1 && ($v = array_pop($stack)) !== null) | |
| $stack[$c-2] += $v; | |
| break; | |
| case '-': | |
| while (($c = count($stack)) > 1 && ($v = array_pop($stack)) !== null) | |
| $stack[$c-2] -= $v; | |
| break; | |
| case '*': | |
| while (($c = count($stack)) > 1 && ($v = array_pop($stack)) !== null) | |
| $stack[$c-2] *= $v; | |
| break; | |
| case '/': | |
| while (($c = count($stack)) > 1 && ($v = array_pop($stack)) !== null) | |
| $stack[$c-2] /= $v; | |
| break; | |
| default: | |
| $stack[] = new \BCMath\Number($token); | |
| break; | |
| } | |
| } | |
| return (string) $stack[0]; | |
| } | |
| $exp = '1 2 3 4 5 + 3 * 4 /'; | |
| echo 'The result is ' . bc($exp) . PHP_EOL; // The result is 11.25 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment