Our focus today is PHP math. Or “PHP maths,” if you prefer British English. We’re not going to teach you the basics of mathematics itself, but just explore some of the common ways we use math in our PHP code and some of the less-clear things that end up super-valuable for web development using the PHP programming language.
We’ll be covering things like basic math, square roots in PHP, the
floor functions, and some basic PHP arithmetic operator examples. Let’s get to it.
Basic Math in PHP: A Lot Like You’d Expect
In PHP, math calculations are written about as you’d expect. If you’ve ever typed a basic arthmetic mathematics formula into a spreadsheet, its the same in PHP. For the four most-basic math operations I think you’ll be so unsurprised that we can just show them all at once. So in PHP math this is all going to work as you’d expect:
$average = (17 + 21 - 1 + 23 + 25 + 7 + 23*3 + 2)/10;
What I hope you see above is that all the basics of math: addition, subtraction, multiplication, division, and parenthesis for order-or-operations are exactly as you expect if you’ve ever done math on a computer.
You use the obvious symbols in the obvious ways for our basic PHP arithmetic operators example. There’s nothing you should be surprised by there. Basic PHP math can be done with basic operators, and there’s no need to understand more complex PHP number functions to do it. That said, we really must get beyond them, and see some examples of PHP math functions. Because they’re the ones that may one day surprise you.
Slightly Less Obvious PHP Maths
Alight time to get into some PHP math functions…
One of the core units of PHP that doesn’t quite linearly match to the way you were taught mathematic in school: PHP functions. In PHP functions are called in a specific way:
function_name($argument, $for, $function);
This looks pretty different from the most abstract way we usually write mathematical expressions. But PHP, because of it’s programming content, will have to use some math functions to make up for limits of it’s (non-mathematical) syntax.
How to Do PHP Exponents: Squared, Cubed, etc in PHP
Math functions are where we get into, for example, writing x2 (x-squared) in PHP. Squared, cubed, all the exponents. PHP squared and cubed number examples will actually look like this:
$two_squared = pow(2, 2); // 4 $three_squared = pow(3, 2); // 9 $two_cubed = pow(2, 3); // 8 $three_cubed = pow(3, 3); // 27
Now, my variable names are more literal than your code doing these operation should be. But hopefully that made this PHP mathematic function example a little more clear. In PHP the
pow function is how we raise a number to a specific mathematical exponent. So we show the number 2 raised to the “5th power” with the function call
pow(2, 5). In this example, the first number is the “base” (the number which has an exponent above it), and the latter number is the “exponent” or the power to which it is raised.
Less common but worth knowing, PHP also uses two astricks
** as an exponention operator since 5.6. So to rewrite the above example using it, this is also all valid PHP:
$two_squared = 2 ** 2; // 4 $three_squared = 3 ** 2; // 9 $two_cubed = 2 ** 3; // 8 $three_cubed = 3 ** 3; // 27
The full PHP.net arithmetic operators example page is worth a quick perusal. It’s where I was reminded of this operator. (BTW, if you’ve done math with a QWERTY keyboard before, you may have written 2-squared as
2^2. Don’t use that in PHP. It’s not going to do what you think. Use
But How do I Do a Square Root in PHP?
From my days with a spreadsheet, I expected PHP to have a
sqrt function, and indeed it does. You’ll call
sqrt to get a the square root. PHP often matches expectations in a glorious way.
So, to see a little bit of code:
$five = sqrt(25); $four = sqrt(16);
As before, our variable name are over-specific. You may also recognize that a square root function is a lot less powerful than than
pow function we covered in the last section. After all, how to I do a cubic (or “nth” root) in PHP? Well, you actually just use
pow or the
** that we covered above.
$five = pow(125, 1/3); $four = 64 ** 1/3;
Also worth realizing, you can even do the square root in PHP this way:
$five = pow(25, 1/2);
All of this is based on the knowledge that the root of a number is the inverse of that number’s power. But I’m not a math teacher, and if you’re confused by what I’ve just said, I’ll unfortunately have to refer you to a math teacher for a more complete explanation. This being the internet, I fortunately found a good-enough explanation of what I’m referring to in this YouTube video:
Yay for learning math!
We’ve Got Most Math-y Ones: Sine, Cosine, Etc
We won’t cover all of the PHP math functions here today. We’d both get bored in that exercise. And PHP.net math functions page is a great source for information about every single on of PHP’s math operators and number functions.
I will briefly highly a few more that I’ve used in the past:
- All the trigonometry functions you expect are in PHP. That mean you’ll find
tan, and more interesting ones like
asinhthe “inverse hyperbolic sine.” (I actually forgot what the last one means even, but I know I learned it in math class once.)
- A big part of trigonometry is the number “pi.” PHP makes that available to you as a function, called
pi(). It also has a constant value defined,
- PHP has lots of number-base conversion functions. Want to make a base-10 number into a base-16 number (for example)?
dechexis here to turn you decimal number into a hexadecimal one.
Like I said, as we get beyond PHP arithmetic operators examples, we start to touch on parts of math you don’t use outside of very specific situations. So we’ll stop there and transition to three weird math functions I use an awful lot.
Practical PHP Math: Rounding Numbers!
The last bit of math I want to cover in PHP today is rounding. PHP has three functions that help us round numbers to a more standard looking value. They are:
round()for when you want to get the correctly rounded number as your math teacher would have liked. Round defaults to no numbers to the right of the decimal place, but it takes an optional second argument. For example, we can get pi’s rounded value of
3.14with a call to
round( M_PI, 2 );. That’s the most basic of PHP math rounding.
- Want to always round down? That’s where the
floorPHP function comes from. Want to get
3in a really weird way?
floor( M_PI )gives you that.
- Want to round up? Get
4in a weird way with
ceil( M_PI ). What on earth does
ceilmean? It’s an abbreviation of “ceiling” and thus (I guess) a fairly reasonable abbreviating for “round up.”
These PHP math
ceiling functions, unlike
round, do not take second argument. So they will never give you decimal values. You’ll probably find yourself using
floor a lot when you want to make sure that your PHP math yield a whole number, or “integer” with a specific bias (toward being bigger or smaller).
All three of these functions:
ceil are very useful as you try to do simple things like give your CSS classes round numbers or round percentages. Which you’ll want to use in a particular place is really a matter of personal preference.
What We’ve Learned about Math in PHP
We’ve specifically omitted a common concept of math in PHP, because it’s just a little to unfamiliar and a little too cool: modulus. Keep an eye out for that, we’ll try to have it to you in the next few weeks.
In the meantime, we hope you feel a lot more confident about the math functions of PHP. PHP “maths” aren’t really super different than what you’ve seen in other computer-izations of mathematics. Once you learn how to write your mathematical equations, it’s that same school math. PHP will be mostly be out of the way. Unfortunately, that doesn’t necessarily make math easy. PHP isn’t that good