Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).
Binary integer literals are available since PHP 5.4.0.
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.
<?php $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) $a = 0b11111111; // binary number (equivalent to 255 decimal) ?>
Formally, the structure for integer literals is:
decimal : [1-9][0-9]* | 0 hexadecimal : 0[xX][0-9a-fA-F]+ octal : 0[0-7]+ binary : 0b[01]+ integer : [+-]?decimal | [+-]?hexadecimal | [+-]?octal | [+-]?binary
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.
<?php $large_number = 2147483647; var_dump($large_number); // int(2147483647) $large_number = 2147483648; var_dump($large_number); // float(2147483648) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // float(50000000000) ?>
<?php $large_number = 9223372036854775807; var_dump($large_number); // int(9223372036854775807) $large_number = 9223372036854775808; var_dump($large_number); // float(9.2233720368548E+18) $million = 1000000; $large_number = 50000000000000 * $million; var_dump($large_number); // float(5.0E+19) ?>
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 towards zero, or the round() function provides finer control over rounding.
<?php var_dump(25/7); // float(3.5714285714286) var_dump((int) (25/7)); // int(3) var_dump(round(25/7)); // float(4) ?>
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! ?>
Please login to continue.