$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;
It kind of depends more broadly on what you're trying to do.
I'm not convinced unsetting a variable is your best bet here.
However, PHP does have an unset function:
unset($var);
To be clear, I agree that checking for emptiness is probably a better idea
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.