Converting to integer
To explicitly 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 automatically converted if an operator, function
or control structure requires an integer argument. You can
also convert a value to integer with the function intval().
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!
Warning
Never cast an unknown fraction to integer, as this can sometimes
lead to unexpected results.
<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>
See for more information the warning about float-precision.
From strings
See String conversion to numbers
From other types
Caution
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. However, do not rely on
this behaviour, as it can change without notice.
|