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.

Yannis
  • 912
  • 2
  • 14
  • 34

3 Answers3

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.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • 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. – Kaii Feb 23 '12 at 16:35
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)
Kaii
  • 20,122
  • 3
  • 38
  • 60
-1

I think ctype_digit() will work in your case.

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67