A PHP package to simplify working with percentages

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, June 01, 2020

Follow me on Twitter as @mattiasgeniar

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. 😬

But why?

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 $previousMonth and $thisMonth.

No more boilerplate needed! 🥳

Installation

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.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.