Integers

suggest change

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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Types:
* Types
* Float
* Null
* Integers

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR