We’ve covered a ton of information about strings in PHP and their associated string functions, now we’ll take a look at working with numbers in PHP. Numbers are important. If you think about it, we deal with numbers and math all day, every day. It helps to be good with numbers for calculating your budget, picking statistical favorites in your office fantasy league football team, investing based on numerical data, and oodles of other scenarios. In PHP just like other programming languages like Python we’ll typically be dealing with whole numbers and decimal based numbers. In programming parlance we’d be referring to integers and floating point numbers respectively. It’s a fairly straightforward topic and can be fun as well, so let’s jump right in to integers and floating point numbers in PHP!
Integers in PHP
When we think of integers, we’re talking about whole numbers. 1, 2, 3, 4, 5 and so on. Integers can also have negative values, so going in the reverse direction is also valid. -1, -2, -3, and so on are all integers as well. We can do simple math with integers and everything works just like it does in Algebra. All of the orders of operation and operator precedence hold true. Parenthesis can be used to assign priority to orders of operation. Check out this example:
<?php
$variable1 = 9;
$variable2 = 4;
echo ((5 + 4 + $variable1) * $variable2) / 4 -3;
?>
As we can see, by following the standard math rules we come up with the answer of 15.
PHP Math Functions
PHP has several math functions that are quite useful, let’s have a look at a few of them.
<?php
echo 'Random Min Max - '. rand(1, 50).'<br>';
echo 'Random - '. rand().'<br>';
echo 'Modulo - '. fmod(30, 8).'<br>';
echo 'Square Root - '. sqrt(75).'<br>';
echo 'Exponential - '. pow(2,8).'<br>';
echo 'Absolute Value - '. abs(0 - 250).'<br>';
?>
Random – 9524
Modulo – 6
Square Root – 8.6602540378444
Exponential – 256
Absolute Value – 250
These functions work just like we would expect according to the standard math rules. Going through the examples, first up is the Random number generation with a minimum and maximum values. Here we provide a minimum of 1 and a maximum of 50. Each time you run this snippet, you’ll get a random whole number between 1 and 50. You can also run this particular function without providing a min or max value. The modulo takes two numbers and divides them. It returns the remainder of that calculation. The square root function calculates the square root of the number you provide to it. Exponential takes two numbers, the number, and the exponent to assign the power of. Lastly in this group of examples is the absolute value. This gives back the absolute value of the expression within it. For example, if the result comes out to a negative value, the absolute value will give you the actual value without the negative.
Increment and Decrement Numbers in PHP
When working in programming, we often need to add to or remove values from a variable during the course of a script executing. There are a few ways to do this. First we’ll look at incrementing a number.
Increment
<?php
$number = 5;
echo $number = $number + 5;
echo '<br>';
$number = 5;
echo $number += 5;
?>
10
These two examples do the same thing, however you can see their syntax is slightly different. The first example takes the number, then it says assign this number plus 5 and provide this to us. In the second example we use the plus equals shorthand notation. Note that it works the same exact way and gives us the same result, but it is easier and faster to type. This works just the same with multiplication, subtraction, and division. Don’t believe it?! Check it out:
<?php
$number = 5;
echo $number = $number - 5;
echo '<br>';
$number = 5;
echo $number -= 5;
echo '<br>';
$number = 5;
echo $number = $number * 5;
echo '<br>';
$number = 5;
echo $number *= 5;
echo '<br>';
$number = 5;
echo $number = $number / 5;
echo '<br>';
$number = 5;
echo $number /= 5;
?>
0
25
25
1
1
Very Cool!
With the approach we were using above, we were dealing with incrementing and decrementing by using the number 5. We can do this with any value that the problem to solve may call for. A very common use case however is simply adding or subtracting one to a number. This is so because when you work with loops in PHP, adding or subtracting 1 to the iterator happens all the time. Let’s see how to do this.
Post Increment or Decrement
This is the most common way to deal with adding or subtracting a value. Have a look at this:
<?php
$number = 7;
echo $number++;
echo '<br>';
$number = 7;
echo $number--;
?>
7
Hey Wait! Those numbers are the same as when we started! This is because we are doing post increment and decrement. You see what happens here is PHP echos out the value first, then increments the variable. If we change up the code just a little, we can see how this works.
<?php
$number = 7;
$result = $number++;
echo $number;
echo '<br>';
$number = 7;
$result = $number--;
echo $number;
?>
6
That’s more like it. In this snippet we make use of a second variable, $result
. So the flow looks like, assign 7 to $number
, assign $number
to $result
then increment $number
, echo out $number
. It’s a little tricky but will become second nature to you after a while.
Pre Increment or Decrement
You’ll notice that in making use of the Pre Increment or Decrement, the ++
or --
goes before the variable, not after. It’s a subtle yet important difference. You can see that when we echo out the value of the variable, the updated value is produced straight away. How is this? Well in this case, PHP assigns 7 to $number
, it then increments $number
by one, and finally produces the value to the screen. The same flow happens with the decrement, and this is why the output is 8 and 6.
<?php
$number = 7;
echo ++$number;
echo '<br>';
$number = 7;
echo --$number;
?>
6
Strings Are Not Numbers
Strings are not numbers and numbers are not strings. Well this would seem painfully obvious, yet it is easy to get tripped up with PHP since it does type conversion on the fly. Consider this snippet:
<?php
$num1 = 1;
$num2 = '1';
if ($num1 !== $num2) {
echo 'not equal<br>';
}
echo $num1 + $num2;
?>
2
Verrrrry Interesting… In the first if statement we say if the first variable is not equal to the second variable, then echo out not equal. This is exactly what happens when the code runs. Note however that we then echo out variable 1, an integer, plus variable two, a string, and we get the number 2. This should seem very strange to you if you’re new to programming. The number 1 plus the letter one can not possibly be 2! What happens with this is that PHP inspects the second variable and does its best to assume what is meant by the string 1 in terms of a numerical value since we are trying to complete a math operation. This is interesting how this type juggling works but you should really make sure you know what types you are dealing with and explicitly set and convert them as needed when programming. Don’t rely on PHP to do it for you lest you find yourself in a world of hurt when you can figure out why things are not working.
Floating Point Numbers in PHP
This brings us to another type of number in PHP, the floating point. So what does this mean? Do these numbers magically float among the clouds? Are they like a balloon filled with helium? No, no they don’t do anything fun like that. Floating point is just a fancy way of saying a number that has decimal places. We use floating points everyday in our lives. Want to buy a coffee? Sure, that’ll be 2.47
please. There you go, you just made a floating point transaction with your friendly Barista. See that, easy as pie.
Why Floating Point?
It may seem odd that with computers we need to have two types of numbers. In the real world, we simply have numbers, and we deal with them accordingly. It turns out computers compute and store numbers differently. Computers store integers and floating points in different ways. Here are a few examples of some floats:
<?php
echo $float = 7.12;
echo '<br>';
echo $float + 5;
echo '<br>';
echo 5/3;
?>
12.12
1.6666666666667
You see we can assign a float to a variable, add a number to a float, or divide a number which returns a floating point value.
Floating Point Functions
Sometimes it will be useful to apply any of the built in PHP functions for floats. We have functions like round
, ceil
, and floor
to do just that. Mainly, these are just simple rounding functions and they do what their name appears as. This snippet gives you an example of how these work:
<?php
$float = 7.12;
echo round($float, 1);
echo '<br>';
echo ceil($float);
echo '<br>';
echo floor($float);
?>
8
7
Is that a Float in your Pocket?
Is that a float in your pocket or are you just happy to see me? Many times you’ll need to check a variable to see if it is a float or an integer. You might also need to simply check to see if it is a numeric value. There are a few easy ways to do this, let’s see how.
<?php
$float = 7.12;
$integer = 5;
echo "Is $integer an integer? ";
if (is_int($integer)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}
echo "Is $float an integer? ";
if (is_int($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}
echo "Is $integer a float? ";
if (is_int($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}
echo "Is $float a float? ";
if (is_float($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}
echo "Is $integer a number? ";
if (is_numeric($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}
echo "Is $float a number? ";
if (is_numeric($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}
?>
Is 7.12 an integer? Nope!
Is 5 a float? Nope!
Is 7.12 a float? Yep!
Is 5 a number? Yep!
Is 7.12 a number? Yep!
The 11 Fun Hacks to Get Your PHP Integers and Floating Point Values Mastered Summary
We covered the beginnings of Integers, Floating Points, and Numeric Values in this action packed episode of learning PHP fundamentals. So far we’ve take a look at the history of PHP, how to work with strings, we covered PHP string functions soup to nuts, and now we’ve got your numbers covered. Stay tuned for even more random bits of awesomeness about PHP to come in the following episodes.