PHP Lessons - Lesson 4 - PHP Numeric Variables
In the previous lesson, we explored string variables. Now, let’s take a look at numeric variables. The simplest type of number is the integer.
Integers in PHP
Integers are whole numbers in the range from –2,147,483,648
to 2,147,483,647
. This range is determined by the 32-bit memory space used to store integers.
Just like other variables in PHP, integers are assigned with a simple assignment statement:
<?php
$x = 5;
$y = -8;
?>
Apart from decimal numbers, PHP also supports other number systems like octal and hexadecimal:
<?php
$i = 456; // decimal
$i = -895; // negative decimal
$i = 0121; // octal (equivalent to 81 in decimal)
$i = 0x1B; // hexadecimal (equivalent to 27 in decimal)
?>
In addition to integers, PHP supports floating-point numbers.
Floating-Point Numbers (float) in PHP
Floating-point numbers are decimal numbers and can be defined like this:
<?php
$pi = 3.14;
?>
Note that the decimal point is a period (.
), not a comma. PHP also supports scientific notation:
<?php
$b = 3.2e5; // equivalent to 320000
$c = 9E-11; // equivalent to 0.00000000009
?>
Floating-point numbers (also called numbers with a floating point) use 64 bits of memory—twice as much as integers.
Often, float values are the result of division:
<?php
$a = 1/3;
print $a;
?>
The result will be:
0.333333333333
But sometimes the result might not be what you expect at first glance:
<?php
$a = 1/3;
$a = $a * 3;
print $a;
?>
Here, PHP will output exactly:
1
If you did this on a calculator, you’d likely get 0.9999999 due to rounding limitations. PHP, however, retains the mathematical precision of operations whenever possible, ensuring accurate results without data loss.