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.


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.

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