How to verify if $_GET exists?

05/09/2020 01:30:01

So, I have some PHP code that looks a bit like this:

<body>
    The ID is 

    <?php
    echo $_GET["id"] . "!";
    ?>

</body>

Now, when I pass an ID like http://localhost/myphp.php?id=26 it works alright, but if there is no ID like just http://localhost/myphp.php then it outputs:

The ID is
Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9
!

I have searched for a way to fix this but I cannot find any way to check if a URL variable exists. I know there must be a way though.

Verified Answer (136 Votes)

08/18/2012 20:15:11

You can use isset function:

if(isset($_GET['id'])) {
    // id index exists
}

You can create a handy function to return default value if index doesn't exist:

function Get($index, $defaultValue) {
    return isset($_GET[$index]) ? $_GET[$index] : $defaultValue);
}

// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');

You can also try to validate it at the same time:

function GetInt($index, $defaultValue) {
    return isset($_GET[$index]) && ctype_digit($_GET[$index])
            ? (int)$_GET[$index] 
            : $defaultValue);
}

// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);
136

Answer #2 (18 Votes)

08/18/2012 20:15:44
   if (isset($_GET["id"])){
        //do stuff
    }
18

Answer #3 (9 Votes)

08/18/2012 20:19:25

Normally it is quite good to do:

echo isset($_GET['id']) ? $_GET['id'] : 'wtf';

This is so when assigning the var to other variables you can do defaults all in one breath instead of constantly using if statements to just give them a default value if they are not set.

9
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.