The common way for check non-empty var is:
if (!empty($var)) { ... }
Why can't we just use:
if ($var) { ... }
They're the same actually, right?
The common way for check non-empty var is:
if (!empty($var)) { ... }
Why can't we just use:
if ($var) { ... }
They're the same actually, right?
!empty($var)
is exactly the same as just $var
, except that with empty
no error will be thrown if $var
doesn't exist. empty
is more or less shorthand for !isset($var) || !$var
.
You should never use empty
if you expect your variable to exist, because then you're just needlessly suppressing error reporting. Only use empty
if you legitimately expect the variable to possibly not exist. This should rarely if ever be the case, if you're initialising your variables properly.
See The Definitive Guide To PHP's isset And empty for an in-depth discussion of this.