3v4l.org

run code in 300+ PHP versions simultaneously
<?php function bc() { $argv = func_get_args(); $string = str_replace(' ', '', "({$argv[0]})"); $operations = array(); if (strpos($string, '^') !== false) $operations[] = '\^'; if (strpbrk($string, '*/%') !== false) $operations[] = '[\*\/\%]'; if (strpbrk($string, '+-') !== false) $operations[] = '[\+\-]'; if (strpbrk($string, '<>!=') !== false) $operations[] = '<|>|=|<=|==|>=|!=|<>'; $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string); while (preg_match('/\(([^\)\(]*)\)/', $string, $match)) { foreach ($operations as $operation) { if (preg_match("/([+-]{0,1}[0-9\.]+)($operation)([+-]{0,1}[0-9\.]+)/", $match[1], $m)) { switch($m[2]) { case '+': $result = bcadd($m[1], $m[3]); break; case '-': $result = bcsub($m[1], $m[3]); break; case '*': $result = bcmul($m[1], $m[3]); break; case '/': $result = bcdiv($m[1], $m[3]); break; case '%': $result = bcmod($m[1], $m[3]); break; case '^': $result = bcpow($m[1], $m[3]); break; case '==': case '=': $result = bccomp($m[1], $m[3]) == 0; break; case '>': $result = bccomp($m[1], $m[3]) == 1; break; case '<': $result = bccomp($m[1], $m[3]) == -1; break; case '>=': $result = bccomp($m[1], $m[3]) >= 0; break; case '<=': $result = bccomp($m[1], $m[3]) <= 0; break; case '<>': case '!=': $result = bccomp($m[1], $m[3]) != 0; break; } $match[1] = str_replace($m[0], $result, $match[1]); } } $string = str_replace($match[0], $match[1], $string); } return $string; } // Exemplo de uso: Operações matemáticas $resultado = bc("(2 + 3) * 4"); echo $resultado; // Saída: 20
Output for 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
Warning: preg_replace(): Unknown modifier 'e' in /in/geCrH on line 13 Deprecated: preg_match(): Passing null to parameter #2 ($subject) of type string is deprecated in /in/geCrH on line 14
Output for 8.1.34, 8.2.27 - 8.2.30, 8.3.0 - 8.3.30
Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead in /in/geCrH on line 13 Deprecated: preg_match(): Passing null to parameter #2 ($subject) of type string is deprecated in /in/geCrH on line 14

preferences:
61.34 ms | 408 KiB | 5 Q