Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.

See also: Arbitrary precision integers and Floating point numbers

Syntax

Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded by a sign (- or +).

If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.

P°φklad 6-1. Integer literals

$a = 1234; # decimal number
$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x1A; # hexadecimal number (equivalent to 26 decimal)
       
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed).

Poznßmka: In PHP there is no such thing as integer-division. 1/2 yields the double 0.5.

Integer overflow

If you specify a number beyond the bounds of the integer-type, it will be interpreted as a double instead.

$large_number =  2147483647;
var_dump($large_number);
// output: int(2147483647)
$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648) 
       

Furthermore, if some function or operator yields a number that is beyond the boundaries of integer, it will also be automatically converted to double.

$million = 1000000;
$large_number =  50000 * $million;
var_dump($large_number);
// output: float(50000000000)
       

Converting to integer

To explicitely convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be autmatically converted if an operator, function or control-structure requires a boolean-argument.

See also type-juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!

Varovßnφ

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

echo (int) ( (0.1+0.7) * 10 ); // echo's 7!
         

See for more information the warning about float-precision.

From other types

Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean.

V²straha

However, do not relay on this behaviour, as it can change without notice.