Integers
An integer is a number of the set
Z = {..., -2, -1, 0, 1, 2, ...}.
See also:
Syntax
Integers can be specified in decimal (base 10), hexadecimal
(base 16), or octal (base 8) notation, optionally preceded by a sign
(- or +).
To use octal notation, precede the number with a 0 (zero).
To use hexadecimal notation precede the number with 0x.
Example #1 Integer literals
<?php
$a = 1234; $a = -123; $a = 0123; $a = 0x1A; ?>
Formally, the structure for integer literals is:
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). PHP
does not support unsigned integers. Integer size
can be determined using the constant PHP_INT_SIZE, and
maximum value using the constant PHP_INT_MAX since
PHP 4.4.0 and PHP 5.0.5.
Warning
If an invalid digit is given in an octal integer (i.e. 8 or 9),
the rest of the number is ignored.
Example #2 Octal weirdness
<?php
var_dump(01090); ?>
Integer overflow
If PHP encounters a number beyond the bounds of the integer
type, it will be interpreted as a float instead. Also, an
operation which results in a number beyond the bounds of the
integer type will return a float instead.
Warning
Unfortunately, there was a bug in PHP which caused this to not always work
correctly when negative numbers were involved. For example, the result of
-50000 * $million is -429496728.
However, when both operands were positive, there was no problem.
This was fixed in PHP 4.1.0.
There is no integer division operator in PHP.
1/2 yields the float 0.5.
The value can be casted to an integer to round it downwards, or
the round() function provides finer control over rounding.
Converting to integer
To explicitly convert a value to integer, use either the
(int) or (integer) casts. However, in
most cases the cast is not needed, since a value will be automatically
converted if an operator, function or control structure requires an
integer argument. A value can also be converted to
integer with the intval() function.
See also: type-juggling.
FALSE will yield 0 (zero), and TRUE will yield
1 (one).
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 doesn't have enough precision to give an exact
integer result. No warning, not even a notice will be issued
when this happens!
From other types
Caution
The behaviour of converting to integer is undefined for other
types. Do not rely on any observed behaviour, as it
can change without notice.
There are no user contributed notes for this page.
|
|