PHP: Check if variable exist but also if has a value equal to something

Sadly that’s the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:

$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));

The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.

Or you can use something like that:

$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $m ) {
    $_GET[$m] = null;
}

Now each required element at least has a default value. You can now use if($_GET[‘myvar’] == ‘something’) without worrying that the key isn’t set.

Update

One other way to clean up the code would be using a function that checks if the value is set.

function getValue($key) {
    if (!isset($_GET[$key])) {
        return false;
    }
    return $_GET[$key];
}

if (getValue('myvar') == 'something') {
    // Do something
}

Leave a Comment