Integers in PHP can be natively specified in base 2 (binary), base 8 (octal), base 10 (decimal), or base 16 (hexadecimal.)
$my_decimal = 42;
$my_binary = 0b101010;
$my_octal = 052;
$my_hexadecimal = 0x2a;
echo ($my_binary + $my_octal) / 2;
// Output is always in decimal: 42
Integers are 32 or 64 bits long, depending on the platform. The constant PHP_INT_SIZE
holds integer size in bytes. PHP_INT_MAX
and (since PHP 7.0) PHP_INT_MIN
are also available.
printf("Integers are %d bits long" . PHP_EOL, PHP_INT_SIZE * 8);
printf("They go up to %d" . PHP_EOL, PHP_INT_MAX);
Integer values are automatically created as needed from floats, booleans, and strings. If an explicit typecast is needed, it can be done with the (int)
or (integer)
cast:
$my_numeric_string = "123";
var_dump($my_numeric_string);
// Output: string(3) "123"
$my_integer = (int)$my_numeric_string;
var_dump($my_integer);
// Output: int(123)
Integer overflow will be handled by conversion to a float:
$too_big_integer = PHP_INT_MAX + 7;
var_dump($too_big_integer);
// Output: float(9.2233720368548E+18)
There is no integer division operator in PHP, but it can be simulated using an implicit cast, which always 'rounds' by just discarding the float-part. As of PHP version 7, an integer division function was added.
$not_an_integer = 25 / 4;
var_dump($not_an_integer);
// Output: float(6.25)
var_dump((int) (25 / 4)); // (see note below)
// Output: int(6)
var_dump(intdiv(25 / 4)); // as of PHP7
// Output: int(6)
(Note that the extra parentheses around (25 / 4)
are needed because the (int)
cast has higher precedence than the division)