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
}
As of PHP7 you can use the Null Coalescing Operator ??
to avoid the double reference:
$_GET['myvar'] = 'hello';
if (($_GET['myvar'] ?? '') == 'hello') {
echo "hello!";
}
Output:
hello!
In general, the expression
$a ?? $b
is equivalent to
isset($a) ? $a : $b
If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:
if ((isset($variable) ? $variable : null) == $value) { }
The only possible downside is that if you're testing for true
/false
- null
will be interpreted as equal to false
.