phpsuperglobals

What is the php function to simultaneously check the existence of a $_GET parameter and access its value


In PHP, to avoid Undefined Index errors, one can write

if(isset $_GET['var1'] && $_GET['var1'] == 'My Matching Text'){
    //do stuff
}

But I remember using a function (or language construct) that I think would allow something like this:

if([THE FUNCTION I'M LOOKING FOR]($_GET['var1']) == 'My Matching Text'){
    //do stuff
}

What is this function whose name I have forgotten?


Solution

  • Are you thinking of the filter_input function?

    if (filter_input(INPUT_GET, 'var1') == 'My Matching Text') {
        //do stuff
    }
    

    It takes a third argument where you can specify different filter types, which can be useful. The default type doesn't filter at all, but it will return the value (or null if the key isn't set) without an undefined index notice.

    I don't know how this compares in terms of performance to using the null coalescing operator like the other answers show, but I would assume this function call would be a little more expensive, so the operator would be a better way to go unless you are going to use one of the filters.