PHP: Calculate the percent difference between two numbers.

This is a small guide on how to calculate the percentage difference between two numbers in PHP. For example, if your original number is 12.50 and you increase it to 14.12; what is the percentage change? i.e. By what percent did it increase by?

Let’s say that we are working on an eCommerce solution for a business that is selling hats online. The owner wants to be able to specify a “special price”. i.e. A reduced price. Whenever a special price has been applied against a product, we need to be able to show the old price, the new price and the percent change (22% cheaper, etc).

Here is an example:

<?php

$oldFigure = 14;
$newFigure = 12.50;

$percentChange = (1 - $oldFigure / $newFigure) * 100;

echo $percentChange;

If you run the PHP code above, you’ll see that the price dropped by -12%.

Here is another example. This time, we are showing how much it increased by:

<?php

$oldFigure = 14;
$newFigure = 17;

$percentChange = (1 - $oldFigure / $newFigure) * 100;

echo $percentChange;

The result is: 17.647058823529% increase.

“I don’t want to show all of the decimal places.”

In cases where you only want to show 2 decimal places, you can use the function number_format:

<?php

$oldPrice = 14;
$newPrice = 17;

$percentChange = (1 - $oldPrice / $newPrice) * 100;

echo number_format($percentChange, 2);

Run the code above and you’ll see that our figure has been formatted into 17.65%.

“I’m getting a minus percentage number.”

When you’re wanting to show a percent drop in price, a minus percentage figure might not be what you’re looking for. Example: You want to print out the text “12% drop in price!” or “Reduced by 5%!” In those cases, a minus percentage number will not work. In those cases, you can simply use the abs function, which converts numbers into absolute numbers:

<?php

$oldFigure = 14;
$newFigure = 10;

$percentChange = (1 - $oldFigure / $newFigure) * 100;

echo abs($percentChange);

The code above will convert -17.647058823529 into 17.647058823529.

“I don’t want any decimal places.”

If you want to remove the decimal point completely, you can use the round function:

<?php

$oldFigure = 14;
$newFigure = 17;

$percentChange = (1 - $oldFigure / $newFigure) * 100;

echo round($percentChange, 0);

The PHP above will output the number 18, simply because 17.647058823529 has been rounded up.