note 113463 added to ref.bc

From: Date: Mon, 14 Oct 2013 13:43:04 +0000
Subject: note 113463 added to ref.bc
Groups: php.notes 
Request: Send a blank email to php-notes+get-196552@lists.php.net to get a copy of this message
Inspired by dawidgarus' implementation, here's my simple bc math helper, it does not support function calls, but supports boolean comparisons and is about ~40% faster. <?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; } ?> ---- Server IP: 69.147.83.199 Probable Submitter: 109.93.218.229 ---- Manual Page -- http://php.net/manual/en/ref.bc.php Edit -- https://master.php.net/note/edit/113463 Del: integrated -- https://master.php.net/note/delete/113463/integrated Del: useless -- https://master.php.net/note/delete/113463/useless Del: bad code -- https://master.php.net/note/delete/113463/bad+code Del: spam -- https://master.php.net/note/delete/113463/spam Del: non-english -- https://master.php.net/note/delete/113463/non-english Del: in docs -- https://master.php.net/note/delete/113463/in+docs Del: other reasons-- https://master.php.net/note/delete/113463 Reject -- https://master.php.net/note/reject/113463 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#196552) next »