Get the ratio of two numbers in PHP

In this article, I am going to guide you to show how to get the ratio of two numbers in PHP. Follow me to see how we can perform this useful task.

I hope, you already know what is the ratio. In high school, we already introduced the concept of ratio in mathematics.

We can easily compare two numbers that can give us the idea with a ratio type representation. For example, if we have 5 kg of potato and 10 kg of mango, then the ratio of mass between the potato and mango will be 1:2. This representation makes some sense to us.

Custom PHP function to get the ratio of two numbers

Now it’s time to write our PHP code that can calculate the ratio of two numbers. Here we are going to create our custom function that can do our task. See the code below:

function calculate_ratio($num_1, $num_2){
    for($n=$num_2; $n>1; $n--) {

        if(($num_1%$n) == 0 && ($num_2%$n) == 0) {

    return $num_1.":".$num_2;


In the above code, we have created our custom PHP function which is with the function name calculate_ratio.

Now, to get the ration of any two numbers, all we need is just to pass those two numbers as the arguments of the function to get the result. As a result, it will return the ratio that we want to get.

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.

I hope this task will be useful to you.

Also, read: Check if our string contains a specific word in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *