PHP: Calculate the ratio between two numbers.

This is a short guide on how to calculate the ratio between two numbers using PHP. This can be useful if you are presenting statistics, etc. Below, I’ve created a custom function that you can use.

What is a ratio?

A ratio allows us to compare two numbers in a way that makes sense to the reader. Essentially, a ratio tells us how much one number contains the other number. Although coders typically stick to calculating percentages when it comes to these sort of things, there may come a use case where you have to display the ratio.

Example.

150 people visit your website and 5 of those people agree to sign up for your newsletter. When you work out the math, that’s a ratio of 1:30. i.e. 1 in every 30 visitors signed up for your newsletter. As a percent, that’s 3.33%.

Using PHP to calculate ratios.

Here’s the PHP function that you came for.

/**
 * Calculate the ratio between two numbers.
 * 
 * @param int $num1 The first number.
 * @param int $num2 The second number.
 * @return string A string containing the ratio.
 */
function getRatio($num1, $num2){
    for($i = $num2; $i > 1; $i--) {
        if(($num1 % $i) == 0 && ($num2 % $i) == 0) {
            $num1 = $num1 / $i;
            $num2 = $num2 / $i;
        }
    }
    return "$num1:$num2";
}


//Example returns 1:2
echo getRatio(2, 4), '<br>';

//Example returns 1:5
echo getRatio(2, 10), '<br>';

In the code above, there are two examples showing you how this function works. Note that this function will return a string, with the resulting numbers being separated by a colon. Obviously, you can modify the return statement to meet your own needs. Or you could use PHP’s explode function to separate them.

I hope that you found this function as useful as I did!

Facebook Comments