Learn how to calculate a positive and negative percentage change between 2 numbers in PHP easily.

Willing to solve a simple percentage change in the server with PHP? The first you need to do, is to think mathematically. You need to retrieve the difference (decrease or increase) between the numbers that you are comparing. This difference needs to be divided between the first number (the one that doesn't change). The result from this operation needs to be multiplied by 100. Making an abstraction of this process in a PHP basic function, we would have:

/**
* Calculates in percent, the change between 2 numbers.
* e.g from 1000 to 500 = 50%
* 
* @param oldNumber The initial value
* @param newNumber The value that changed
*/
function getPercentageChange($oldNumber, $newNumber){
    $decreaseValue = $oldNumber - $newNumber;

    return ($decreaseValue / $oldNumber) * 100;
}

Note that if you change the orders of the old and new number, the answer would be different, so be sure that the first argument is the first version of the value, that means the one that didn't change and as second argument the value that changed.

Examples

The following examples show different cases of a percentage change both positive (decrease) as negative (increase) according to the point of view:

Note

A negative value indicates a percentage increase.

// X = 500
// Y = 234
// % = 53.2
echo getPercentageChange(500, 234);

// X = 1000
// Y = 890
// % = 11
echo getPercentageChange(1000, 890);

// X = 5
// Y = 2
// % = 60
echo getPercentageChange(5, 2);

// X = 100
// Y = 120
// % = -20
// Note: negative as it incremented 20%
echo getPercentageChange(100, 120);


// X = 500
// Y = 500
// % = 0
// Note: no percent change
echo getPercentageChange(500, 500);

Where can this function be used

For example, if you are working with image compression algorithms, you may want to display a human readable value in percent that indicates how much was compressed from the intial image, where the oldNumber is the original filesize e.g 1MB and the newNumber is 500KB which would result in a decrease of 50%.

Happy coding !


Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Become a more social person

Sponsors