Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to get a ratio in PHP of multiple numbers?

I've adapted this from an example that I found on the 'net...

function ratio($a, $b) {
    $_a = $a;
    $_b = $b;

    while ($_b != 0) {

        $remainder = $_a % $_b;
        $_a = $_b;
        $_b = $remainder;   
    }

    $gcd = abs($_a);

    return ($a / $gcd)  . ':' . ($b / $gcd);

}

echo ratio(9, 3); // 3:1

Now I want it to use func_get_args() and return the ratios for multiple numbers. It looks like a recursive problem, and recursion freaks me out (especially when my solutions infinitely loop)!

How would I modify this to take as many parameters as I wanted?

Thanks

like image 254
alex Avatar asked Aug 10 '10 10:08

alex


People also ask

How do you find the ratio in PHP?

Below is the usage of our custom function: //This example will give the result 1:3 echo calculate_ratio(4, 12), '<br>'; //This example will give the result 1:2 echo calculate_ratio(12, 24), '<br>'; If you run the code on the PHP server, then you will be able to see the ratio of the numbers passes to the function.

How do you calculate multiple ratios?

Step 1: Find the total number of parts in the ratio by adding the numbers in the ratio together. Step 2: Find the value of each part in the ratio by dividing the given amount by the total number of parts. Step 3: Multiply the original ratio by the value of each part.

How do you find the ratio of 4 numbers?

For example, if A is five and B is 10, your ratio will be 5/10. Solve the equation. Divide data A by data B to find your ratio. In the example above, 5/10 = 0.5.


1 Answers

1st, try this gcd function http://php.net/manual/en/function.gmp-gcd.php Or else you must define a gcd function like

    function gcd($a, $b) {
        $_a = abs($a);
        $_b = abs($b);

        while ($_b != 0) {

            $remainder = $_a % $_b;
            $_a = $_b;
            $_b = $remainder;   
        }
        return $a;
    }

Then modify the ratio function

    function ratio()
    {
        $inputs = func_get_args();
        $c = func_num_args();
        if($c < 1)
            return ''; //empty input
        if($c == 1)
            return $inputs[0]; //only 1 input
        $gcd = gcd($input[0], $input[1]); //find gcd of inputs
        for($i = 2; $i < $c; $i++) 
            $gcd = gcd($gcd, $input[$i]);
        $var = $input[0] / $gcd; //init output
        for($i = 1; $i < $c; $i++)
            $var .= ':' . ($input[$i] / $gcd); //calc ratio
        return $var; 
    }
like image 175
Bang Dao Avatar answered Nov 15 '22 05:11

Bang Dao