Integer in PHP

I. Integer

Integers are numbers without any decimal point.

For example: -1, 0, 1.

When an integer goes out of its max and min value, it will change into the float data type.

$x = PHP_INT_MAX + 1;
var_dump($x); // float(9223372036854775808)

If we have a large number, we can use underscore for readability.

$x = 1_000_000_000;
var_dump($x); // int(1000000000)

II. Check if a variable is an integer

To check, we can use the function is_int().

$a = 12;
var_dump(is_int($a)); // bool(true)

III. Casting

You can cast a value by using an int or integer.

$a = (int) 12;
var_dump($a); // int(12)

$b = (int) true;
var_dump($b); // int(1)

$c = (int) false;
var_dump($c); // int(0)

$d = (int) 6.6;
var_dump($d); // int(6) because the floating number will lose the decimal point and get rounded down.

$e = (int) "8.3";
var_dump($e); // int(8)

$f = (int) "hello";
var_dump($f); // int(0) because the string cannot be converted into integer.

$g = (int) null;
var_dump($g); // int(0)