I created a PHP package that can make it easier to work with percentages in any PHP application.
How does it work?
You can use it as a readable percentage converter. It can do the easy stuff (how much is X of Y) and the slightly harder stuff (how much is the X extension of Y to Z).
<?php use Mattiasgeniar\Percentage\Percentage; // What's the percentage increase from 100 to 120? Percentage::differenceBetween(100, 120); // 20% // What's the absolute percentage change from 100 to 80? // (uses the abs() function) Percentage::absoluteDifferenceBetween(100, 80); // 20%, not -20% // How much is 120 compared to 100? Percentage::calculate(120, 100); // 120% // How much is 50 compared to 100? Percentage::calculate(50, 100); // 50% // What is 20% of 200? Percentage::of(20, 200); // 40 // What is the 140% extension from 3 to 2? Percentage::extension(140, 3, 2); // 1.6 // What is the 140% extension from 1 to 2? Percentage::extension(140, 1, 2); // 2.4
None of this is rocket science, of course. It’s just a wrapper around some simple mathematics, but it confuses me every time I have to calculate it. 😬
I hate seeing the same calculations happen over & over again in my code. It’s usally 2 or 3 lines of the same code to calculate percentages in VAT, referral discounts, commissions, relative increases/decreases, …
Now, I get to replace them all with a simple wrapper function like
Percentage::differenceBetween($previousMonth, $thisMonth), which will give me a percentage increase or decrease for the revenue between
No more boilerplate needed! 🥳
By the virtue of Composer, the PHP package manager, installation is as simple as:
composer require mattiasgeniar/php-percentages
Include the namespace somewhere in your code, and you’re done:
<?php use Mattiasgeniar\Percentage\Percentage; $difference = Percentage::differenceBetween(100, 120);
The code is freely available on Github.