PHP Numbers
A number in PHP is a value for counting and maths, written without quotes. An integer is a whole number, and a float is a number with a decimal point.
Three checks, all true
<?php
var_dump(is_int(42));
var_dump(is_float(3.5));
var_dump(is_numeric("42"));Division can give an integer
The second division has a whole result, so its type is int instead of float.
<?php
var_dump(7 / 2);
var_dump(6 / 2);echo hides the full float
The two tools disagree, and the var_dump line shows the value PHP actually stored.
<?php
echo 0.1 + 0.2, "\n";
var_dump(0.1 + 0.2);Remainders with the % operator
The % operator gives the remainder left after whole division.
<?php
echo 7 % 2, "\n";
echo -7 % 2, "\n";Example
<?php
$total = 25;
$people = 2;
$share = $total / $people;
echo $share, "\n";
echo $total % $people, "\n";Key points
- Number values take part in arithmetic directly, with no quotes around them.
- Use is_int to check whether a value is an integer.
- Use is_float to check whether a value is a float.
- Use is_numeric to check whether a value is a number or numeric text.
- Division gives an integer when the result is whole, and a float when it is not.
- Floats are stored approximately, so a sum can carry a tiny hidden error.
- echo rounds a float for display, and var_dump shows the stored value in full.
In this example, a bill of 25 is split between 2 people. Division gives each share as the float 12.5. The % operator gives 1, the amount left over after a whole split.
Note
The sign of a remainder follows the first number, so -7 % 2 gives -1.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
What does var_dump(6 / 2); print?