Skip to content

Instantly share code, notes, and snippets.

@D1360-64RC14
Created October 10, 2025 18:52
Show Gist options
  • Select an option

  • Save D1360-64RC14/c147a9d88305fc6885c212fb83c5edcd to your computer and use it in GitHub Desktop.

Select an option

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.
<?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