You need isset()
in case $str
is possibly undefined:
if (isset($str) && $str !== '') {
// variable set, not empty string
}
Using !empty()
would have an important caveat: the string '0'
evaluates to false.
Also, sometimes one wants to check, in addition, that $str
is not something falsy, like false
or null
[1]. The previous code doesn't handle this. It's one of the rare situations where loose comparison may be useful:
if (isset($str) && $str != '') {
// variable set, not empty string, not falsy
}
The above method is interesting as it remains concise and doesn't filter out '0'
. But make sure to document your code if you use it.
Otherwise you can use this equivalent but more verbose version:
if (isset($str) && (string) $str !== '') {
// variable set, not empty string, not falsy
}
Of course, if you are sure $str
is defined, you can omit the isset($str)
from the above codes.
Finally, considering that '' == false
, '0' == false
, but '' != '0'
, you may have guessed it: PHP comparisons aren't transitive (fun graphs included).
[1] Note that isset()
already filters out null
.