How to Validates value as integer in PHP ?


There are several ways to validate a value as an integer in PHP:

  • Using the is_int() function: This function checks if a variable is an integer or not. It returns true if the variable is an integer, and false otherwise.

Example:

$value = 10;
if (is_int($value)) {
    echo "The value is an integer";
} else {
    echo "The value is not an integer";
}

Output:

The value is an integer
  • Using the filter_var() function: This function can be used to validate and sanitize different types of data, including integers. The FILTER_VALIDATE_INT filter can be used to validate an integer value. It returns the integer value if the input is valid, and false otherwise.

Example:

$value = "10";
if (filter_var($value, FILTER_VALIDATE_INT) !== false) {
    echo "The value is an integer";
} else {
    echo "The value is not an integer";
}

Output:

The value is an integer
  • Using regular expressions: Regular expressions can be used to validate if a string contains only integer values. The preg_match() function can be used to match a regular expression pattern against a string.

Example:

$value = "10";
if (preg_match('/^[0-9]+$/', $value)) {
    echo "The value is an integer";
} else {
    echo "The value is not an integer";
}

Output:

The value is an integer


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.