Skip to content

Instantly share code, notes, and snippets.

@latik
Forked from blackakula/PHP Calculator
Created January 15, 2019 18:05
Show Gist options
  • Select an option

  • Save latik/8bc62f71fd4951afc652d6319e0f17c0 to your computer and use it in GitHub Desktop.

Select an option

Save latik/8bc62f71fd4951afc652d6319e0f17c0 to your computer and use it in GitHub Desktop.
<?php
function perform($operations, $expr) {
do {
$positions = array_filter(array_map(function ($symbol) use (&$expr) {
return strrpos($expr, $symbol);
}, array_keys($operations)), function ($pos) {
return $pos !== false;
});
if (empty($positions)) {
break;
}
$last = max($positions);
$expr = $operations[$expr[$last]](calc(substr($expr, 0, $last)), calc(substr($expr, $last + 1)));
} while (true);
return $expr;
}
function calc($expr) {
while (strpos($expr, '(') !== false) {
preg_match('/^(.*)\(([^)]+)\)(.*)$/', $expr, $matches);
$expr = $matches[1] . calc($matches[2]) . $matches[3];
}
$expr = perform([
'+' => function ($a, $b) { return $a + $b; },
'-' => function ($a, $b) { return $a - $b; },
], $expr);
$expr = perform([
'*' => function ($a, $b) { return $a * $b; },
'/' => function ($a, $b) { return $a / $b; },
], $expr);
return floatval(trim((string)$expr));
}
echo calc('100-(4+4) * (2*(3 + 2))+2*10 / 5');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment