PHP: Check if variable exist but also if has a value equal to something
Solution 1
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
}
Solution 2
As of PHP7 you can use the Null Coalescing Operator ??
to avoid the double reference:
// $_GET['myvar'] isn't set...
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
// $_GET['myvar'] is set but != 'hello'
$_GET['myvar'] = 'farewell';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
// $_GET['myvar'] is set and == 'hello'
$_GET['myvar'] = 'hello';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
Output:
goodbye!
goodbye!
hello!
Code demo on 3v4l.org
In general, the expression
$a ?? $b
is equivalent to
isset($a) ? $a : $b
Note that in the code example it is necessary to place parentheses around $_GET['myvar'] ?? ''
as ==
has higher precedence than ??
and thus
$_GET['myvar'] ?? '' == 'hello'
would evaluate to:
$_GET['myvar'] ?? ('' == 'hello')
which would be true as long as $_GET['myvar']
was set and "truthy" (see the manual) and false otherwise (since '' == 'hello'
is false).
Precedence code demo on 3v4l.org
Solution 3
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
.
Solution 4
As mellowsoon suggest, you might consider this approach:
required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $key => $default ) {
$_GET[$key] = $default ;
}
You put the default values and set the not recieved parameters to a default value :)
Related videos on Youtube
Mariz Melo
Updated on November 24, 2020Comments
-
Mariz Melo over 3 years
I have (or not) a variable
$_GET['myvar']
coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:What I'm doing and think is not the best way to do:
if(isset($_GET['myvar']) && $_GET['myvar'] == 'something')
: do somethingMy question is, exist any way to do this without declare the variable twice?
That is a simple case but imagine have to compare many of this
$myvar
variables.-
Your Common Sense over 13 yearsPHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...
-
-
Your Common Sense over 13 yearsJust define all your variables. That's the point of all that mess.
-
Mariz Melo over 13 yearsWell I saw this around there, just hoping be possible without using arrays, thanks.
-
Mariz Melo over 13 yearsThank you Pekka, is really very boring do that.
-
Mariz Melo over 13 yearsSometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.
-
Pekka over 13 years@Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.
-
mellowsoon over 13 yearsUpdated my answer to show a possible way to do this without using another array.
-
Mariz Melo over 13 yearsPekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.
-
Keegan Crain over 13 yearsAnd it fires a notice, if the myvar index doesn't exist.
-
DanMan over 13 yearsTrue, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).
-
Ross Snyder over 13 yearsOof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.
-
Matt Browne over 10 yearsUnfortunately this triggers a PHP notice if the array key doesn't exist, does it not?
-
Dan H over 9 yearsNope. This is comparing TRUE/FALSE against 'something'.
-
trincot over 7 yearsIt is better to suggest
===
than==
, as it will not have the downside you mention. -
kmoney12 over 7 yearsthis will still fire an error notice when you call
_FX('param')
-
Taku Yoshi almost 5 yearsIf you use PHP7 it can be simpler
if (($variable ?? null) === $value)
. -
RedDragonWebDesign over 4 yearsUpvote the below answer that mentions
($var ?? 'value')
. That's the most concise way to do it now thanks to PHP 7. -
HaLeiVi almost 3 yearsWhat would happen if I omit the parenthesis?
-
Nick almost 3 years@HaLeiVi because of operator precedence (
==
is higher than??
),$_GET['myvar'] ?? '' == 'hello'
would evaluate as$_GET['myvar'] ?? ('' == 'hello')
so it would evaluate to true if either$_GET['myvar']
is unset (since'hello'
is "truthy") or if$_GET['myvar']
is a "truthy" value (see php.net/manual/en/language.types.boolean.php) -
iWasCloud almost 2 yearsthis will always be false, code inside if-block will never run.