MultiDev
MultiDev

Reputation: 10649

Multiple PHP IF conditions not working

I am trying to make sure the GET string is set in the URL and that it's value is an integer, but I can't get this to work.

if (isset($_GET['allusers']) && is_int($_GET['allusers'])) {

    echo "works";

}

Am I doing something wrong with my parentheses?

Upvotes: 1

Views: 191

Answers (4)

Emil Vikström
Emil Vikström

Reputation: 91963

Use ctype_digit if you are expecting only non-negative integers. This will give the best result in those cases since it allows only the numbers 0-9.

Note that is_numeric will return true for strings which can be converted to integers, both negatives and floats. A few examples of what is_numeric will consider to be true:

  • 0xF5 (hexadecimal)
  • -.0e-000 (a strange way of expressing 0.0)
  • -0.4

Upvotes: 0

shreyas
shreyas

Reputation: 208

In your code

isset($_GET['allusers'])

will be evaluated to be true but is_int($_GET['allusers']) will not as the value of $_GET is a string not int you can modify your code as

if (isset($_GET['allusers']) && is_int(intval($_GET['allusers']))) {

    echo "works";

}

This will work

Upvotes: 0

sachleen
sachleen

Reputation: 31131

is_int returns false on a string, which is what a GET variable will be.

var_dump(is_int("23"));
bool(false)

You should be using is_numeric instad.

Upvotes: -1

Joseph Silber
Joseph Silber

Reputation: 219936

A $_GET variable can't be an integer. It'll always be a string.

To test is it's a numeric string, use is_numeric():

if ( isset($_GET['allusers']) && is_numeric($_GET['allusers']) )
{
    echo "works";
}

Upvotes: 5

Related Questions