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 returnstrue
if the variable is an integer, andfalse
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. TheFILTER_VALIDATE_INT
filter can be used to validate an integer value. It returns the integer value if the input is valid, andfalse
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