$num = 1;
$var = ''
if ($num == 1) {
$var = 'ONE';
}
if (isset($var)) {
echo $var;
}
// Result: ONE
In the above example, which is best practice when checking against isset()
?
$var = '';
or
$var = null;
$num = 1;
$var = ''
if ($num == 1) {
$var = 'ONE';
}
if (isset($var)) {
echo $var;
}
// Result: ONE
In the above example, which is best practice when checking against isset()
?
$var = '';
or
$var = null;
By setting $var = '';
near the top, isset
will return true
every time. What you want, is to check if the $var
is empty
.
Change:
if (isset($var)) {
echo $var;
}
to
if (!empty($var)) {
echo $var;
}
Otherwise, simply remove the original $var = '';
near the top and you can continue to use isset
.