Integers and Floats

As we discussed in Chapter 2, PHP supports both integer and floating-point numbers. PHP stores integers as a 32-bit signed word, providing a range of integers from -2147483647 to +2147483647. PHP automatically converts numbers that overflow out of this range to floats. You can see this behavior by adding one to the largest integer value:

// Largest positive integer (for a 32 bit signed integer)
$variable =  2147483647;

// prints int(2147483647)
var_dump($variable);

$variable++;

// prints float(2147483648)
var_dump($variable);

Floating-point numbers can store a wide range of values, both very large and very small, by storing a mantissa and an exponent. However a floating-point number can't precisely represent all numbers—for example, the fraction 2/3—and some precision can be lost.

Integers can be represented in a decimal, hexadecimal, or octal notation:

$var = 42;        // a positive integer
$var = -186;      // a negative integer
$var = 0654;      // 428 expressed as an octal number
$var = 0xf7;      // 247 expressed as a hexadecimal number

Floating-point numbers can represented in a decimal or exponential notation:

$var = 42.0;      // a positive float
$var = -186.123;  // a negative float
$var = 1.2e65;    // a very big number
$var = 10e-75;    // a very small number

Apart from the basic operators +, -, /, *, and %, PHP provides the usual array of mathematical library functions. In this section, we present some of the library functions that are used with integer and float numbers.

Absolute Value ...

Get Web Database Applications with PHP and MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.