Doing math in PHP
So, PHP comes with a handy toolbox for doing math without needing to write formulas from scratch. Whether you’re handling subscription totals, affiliate commissions, or just rounding values in a report, these built-in functions save you time.
The pi() function simply gives you π — 3.14159 and all that. You’d rarely use it unless you’re doing something scientific or geometric, but it’s good to know it’s there.
min() and max() are much more common. They find the smallest or largest number in a list — handy if you’re trying to determine, say, the lowest commission in a payout batch or the highest membership renewal amount:
echo(min(0, 150, 30, 20, -8, -200)); // lowest value
echo(max(0, 150, 30, 20, -8, -200)); // highest value
Then you’ve got abs(), which gives you the absolute value — basically, it turns negatives into positives:
echo(abs(-6.7)); // returns 6.7
That’s useful when working with balances or deltas, where the direction (positive/negative) doesn’t matter.
sqrt() finds the square root of a number. You probably won’t need it for memberships or link tracking, but it’s good for completeness:
echo(sqrt(64)); // 8
round() is something you’ll see a lot, especially when dealing with decimals — like rounding a recurring payment to two decimal places for display:
echo(round(0.60)); // 1
echo(round(0.49)); // 0
And finally, rand() — this one generates random numbers:
echo(rand()); // random number
You can also specify a range:
echo(rand(10, 100)); // random number between 10 and 100
Sometimes you might use this to create unique identifiers, test data, or randomized coupon codes — though for real applications, you’d want more secure randomization functions.