Y Kal Y Kal - 8 months ago 16
PHP Question

How to check if string value returned from text input is integer

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.


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.