Checking If a Variable Is an Integer in PHP

Checking if a variable is an integer in PHP

Using is_numeric() for checking if a variable is an integer is a bad idea. This function will return TRUE for 3.14 for example. It's not the expected behavior.

To do this correctly, you can use one of these options:

Considering this variables array :

$variables = [
"TEST 0" => 0,
"TEST 1" => 42,
"TEST 2" => 4.2,
"TEST 3" => .42,
"TEST 4" => 42.,
"TEST 5" => "42",
"TEST 6" => "a42",
"TEST 7" => "42a",
"TEST 8" => 0x24,
"TEST 9" => 1337e0
];

The first option (FILTER_VALIDATE_INT way) :

# Check if your variable is an integer
if ( filter_var($variable, FILTER_VALIDATE_INT) === false ) {
echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

The second option (CASTING COMPARISON way) :

# Check if your variable is an integer
if ( strval($variable) !== strval(intval($variable)) ) {
echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

The third option (CTYPE_DIGIT way) :

# Check if your variable is an integer
if ( ! ctype_digit(strval($variable)) ) {
echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

The fourth option (REGEX way) :

# Check if your variable is an integer
if ( ! preg_match('/^\d+$/', $variable) ) {
echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

php check to see if variable is integer

try ctype_digit

if (!ctype_digit($_POST['id'])) {
// contains non numeric characters
}

Note: It will only work with string types. So you have to cast to string your normal variables:

$var = 42;
$is_digit = ctype_digit((string)$var);

Also note: It doesn't work with negative integers. If you need this you'll have to go with regex. I found this for example:

EDIT: Thanks to LajosVeres, I've added the D modifier. So 123\n is not valid.

if (preg_match("/^-?[1-9][0-9]*$/D", $_POST['id'])) {
echo 'String is a positive or negative integer.';
}

More: The simple test with casting will not work since "php" == 0 is true and "0" === 0 is false!
See types comparisons table for that.

$var = 'php';
var_dump($var != (int)$var); // false

$var = '0';
var_dump($var !== (int)$var); // true

What's the correct way to test if a variable is a number in PHP?

Use is_numeric() if you want it to accept floating point values, and ctype_digit() for integers only.

PHP check if variable from $_GET is integer


if (!isset($_GET['id'])) {
$errors[] = 'Empty user id';
} else if (!ctype_digit($_GET['id'])) {
$errors[] = 'Invalid id';
} else {
$num_user_id = (int)$_GET['id'];
}

That covers all possibilities: not set and not numeric.

That is if you need to differentiate your error messages between not set and not numeric. Otherwise filter_input is something you should look at.


Arguably you should probably be more relaxed about the specific invalidity; an invalid id is an invalid id and it hardly matters why it's invalid. There are more reasons why an id could be invalid than why it is valid. Caring about all of these reasons individually is not necessarily worth the effort.

I'm assuming that you're fetching a user record from a database with this id; your error control should probably more follow this logic:

  • if $_GET['id'] is not set at all:

    • error 400, bad request
  • else fetch database record with given id, not caring at all what the id looks like (but be aware of what invalid values might cast to and whether you might need to care about that after all)

    • if no record found:

      • error 404, not found
    • else:

      • display page

To that extend, filter_input is perfect:

if (!$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
header("HTTP/1.0 400 Bad Request");
exit;
}

if (!$user = get_user_record($id)) {
header('HTTP/1.0 404 Not Found');
exit;
}

echo $user;

How can I find whether 0 is integer or not in php

i'm recommendation to use you with is_numeric

if (is_numeric(0)) { echo "Yes"; } else { echo "No"; } 
// OUTPUT = YES

DEMO

How to check if a string is made up of integers in PHP

Short version:

Use ctype_digit($_REQUEST['age'])

Long version:

Your problem, as you've found when you use gettype, is that $_REQUEST returns a string. Even if that string is an integer semantically, like 16, it would still be a string-type and not an integer-type variable. You're getting different results from the two tests because they test different things:

  • is_numeric tests whether a string contains an "optional sign, any number of digits, optional decimal part and optional exponential part" according to the PHP docs. In your case, the string does only contain digits, so the test returns True.
  • is_int tests whether the variable's type is an integer - which it won't be, because it's being returned by $_REQUEST.

That's why is_numeric returns True while is_int returns False: the string only contains numbers (and so "is numeric") but still technically has a string type, not an integer type (and so "isn't an int"). Of course, is_numeric isn't sufficient for integer testing, because it will return True if the string has a decimal or uses scientific notation, i.e. is numeric but not an integer.

To test if the $_REQUEST is an integer, regardless of technical type, you can test whether all the characters in the string are digits (and thus the string as a whole is an integer). For this you can use ctype_digit:

ctype_digit($_REQUEST['age'])

This will return True for 16 but not for 16.5 or 16e0 - weeding out the integers from the numeric non-integers.

Check if variable is a number and positive integer in PHP?

To check if a string input is a positive integer, i always use the function ctype_digit. This is much easier to understand and faster than a regular expression.

if (isset($_GET['p']) && ctype_digit($_GET['p']))
{
// the get input contains a positive number and is safe
}

Checking if php variable is a number or not

Try is_numeric.

Finds whether the given variable is numeric. Numeric strings consist
of optional sign, any number of digits, optional decimal part and
optional exponential part. Thus +0123.45e6 is a valid numeric value.
Hexadecimal notation (0xFF) is allowed too but only without sign,
decimal and exponential part.



Related Topics



Leave a reply



Submit