['precedence' => 4, 'order' => 1], '*' => ['precedence' => 3, 'order' => -1], '/' => ['precedence' => 3, 'order' => -1], '+' => ['precedence' => 2, 'order' => -1], '-' => ['precedence' => 2, 'order' => -1], ]; $output = []; $equation = \str_replace(' ', '', $equation); $equation = \preg_split('/([\+\-\*\/\^\(\)])/', $equation, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); if ($equation === false) { return []; // @codeCoverageIgnore } $equation = \array_filter($equation, function($n) { return $n !== ''; }); foreach ($equation as $i => $token) { if (\is_numeric($token)) { $output[] = $token; } elseif (\strpbrk($token, '^*/+-') !== false) { $o1 = $token; $o2 = \end($stack); while ($o2 !== false && \strpbrk($o2, '^*/+-') !== false && (($operators[$o1]['order'] === -1 && $operators[$o1]['precedence'] <= $operators[$o2]['precedence']) /*|| ($operators[$o1]['order'] === 1 && $operators[$o1]['precedence'] < $operators[$o2]['precedence'])*/) ) { // The commented part above is always FALSE because this equation always compares 4 < 2|3|4. // Only uncomment if the opperators array changes. $output[] = \array_pop($stack); $o2 = \end($stack); } $stack[] = $o1; } elseif ($token === '(') { $stack[] = $token; } elseif ($token === ')') { while (\end($stack) !== '(') { $output[] = \array_pop($stack); } \array_pop($stack); } } while (\count($stack) > 0) { $output[] = \array_pop($stack); } /** @var string[] $output */ return $output; } }