There is a more elegant way to do this:
// Recursive function to compute gcd (euclidian method) function gcd ($a, $b) { return $b ? gcd($b, $a % $b) : $a; } // Then reduce any list of integer echo array_reduce(array(42, 56, 28), 'gcd'); // === 14
If you want to work with floating points, use the approximation:
function fgcd ($a, $b) { return $b > .01 ? fgcd($b, fmod($a, $b)) : $a;
You can use closure in PHP 5.3:
$gcd = function ($a, $b) use (&$gcd) { return $b ? $gcd($b, $a % $b) : $a; };
source share