How to check if a variable is an Integer in PHP?
Which methods are available in PHP to check if a variable is an Integer? In this tutorial, we are going to see how to check if a variable is an Integer in PHP.
is_int()
The function is_int($var) returns whether the passed variable is an Integer or not:
<?php var_dump( is_int(1) ); // true var_dump( is_int(0) ); // true var_dump( is_int(-1) ); // true var_dump( is_int(1.0) ); // false var_dump( is_int('1') ); // false var_dump( is_int(true) ); // false var_dump( is_int(new stdClass()) ); // false ?>
Output:
bool(true) bool(true) bool(true) bool(false) bool(false) bool(false) bool(false)
Test for Integer parameters
It makes sense to use is_int() to check function parameters:
<?php function square($val) { if (!is_int($val)) { echo("The number passed is not an integer.\n"); } else { echo("Square of $val: ".($val * $val)."\n"); } } square(2); square(0.4); square("StackHowTo"); square(true); ?>
Output:
Square of 2: 4 The number passed is not an integer. The number passed is not an integer. The number passed is not an integer.