This is a short tutorial on how to increase or decrease a number by a given percent in PHP. In this particular example, we will be adding 2.25% to 100 (i.e. we will be increasing 100 by 2.25%).
Let’s take a look at some example PHP code:
<?php //The percent that we want to add on to our number. $percentageChange = 2.25; //Our original number. $originalNumber = 100; //Get 2.25% of 100. $numberToAdd = ($originalNumber / 100) * $percentageChange; //Finish it up with some simple addition $newNumber = $originalNumber + $numberToAdd; //Result is 102.25 echo $newNumber;
The code snippet above is pretty simple:
- We specified that we wanted to increase our original number by 2.25% (always use decimals). We also specified that our original number is 100.
- We worked out what 2.25% of 100 is by dividing the original number by 100 and multiplying it by the percentage decimal. (Read: Calculating the percentage of a given number in PHP).
- We then added that figure onto our original number.
To decrease the figure by 2.25%, we can simply assign -2.25 to our $percentageChange variable (i.e. place a minus sign in front of the figure).
<?php //The percent that we want to change our number by. $percentageChange = -2.25; //Our original number. $originalNumber = 100;
As you can see, it’s actually pretty simple :)