2

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.

4

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

there are many ways to do this but personally i prefer explicit conversions over implicit ones because they are much more expressive. also checking for the maximum integer size is a good idea.
4

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\n";
} else {
    echo "is not an integer\n";
}
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)

1 Comment

is_numeric() works but I need to know also if number is integer.
-1

I think ctype_digit() will work in your case.

1 Comment

Please give some details. Or Place it in comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.