I also get confused how to check if a variable is false
/null
when returned from a function.
When to use empty()
and when to use isset()
to check the condition ?
The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.
The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.
When converting to bool, the following values are considered false : the boolean false itself. the integer 0 (zero)
PHP isset() Function The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
For returns from functions, you use neither isset
nor empty
, since those only work on variables and are simply there to test for possibly non-existing variables without triggering errors.
For function returns checking for the existence of variables is pointless, so just do:
if (!my_function()) { // function returned a falsey value }
To read about this in more detail, see The Definitive Guide To PHP's isset
And empty
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With