I have a form where users search for keywords.
I want to check if users submit a number (integer) instead of a keyword.
I use this:
$keyword = $_REQUEST["keyword"];
if (is_int($keyword)) {
echo 'true';
} else {
echo 'false';
}
but it always returns false even when the value submitted is integer.
is_int
checks to see whether the variable is of integer type. What you have is a string whose characters happen to represent an integer.
Try:
if (is_numeric($keyword) && is_int(0+$keyword))
The 0+
will implicitly convert the following to a number type, so you'll end up with the numeric value of the string if possible. Calling is_numeric
first ensures you aren't converting garbage.
is_int()
is for type safe comparison, so the string that is received from the browser always evaluates to false
.
If you really need to check if a variable is an integer
you can use this handy function:
function str_is_int($number) {
// compare explicit conversion to original and check for maximum INT size
return ( (int)$number == $number && $number <= PHP_INT_MAX );
// will return false for "123,4" or "123.20"
// will return true for "123", "-123", "-123,0" or "123.0"
}
Note: you should replace PHP_INT_MAX with the maximum integer size of your target system - e.g. your database.
in the docs of is_int()
you can read this:
is_int — Find whether the type of a variable is integer
bool is_int ( mixed $var )
Note:
To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric()
.
Example:
<?php
if (is_int(23)) {
echo "is integer
";
} else {
echo "is not an integer
";
}
var_dump(is_int(23));
var_dump(is_int("23"));
var_dump(is_int(23.5));
var_dump(is_int(true));
?>
The above example will output:
is integer
bool(true)
bool(false)
bool(false)
bool(false)
I think ctype_digit()
will work in your case.