Armin Sam Armin Sam - 1 month ago 5
PHP Question

Why isset(null) throws an error but empty(null) not?

I just came across a strange situation. When I try the following code in

$ php -a
, I receive an error:

php > var_dump(isset(null));



PHP Fatal error: Cannot use isset() on the result of an expression
(you can use "null !== expression" instead) in php shell code on line
1


But when I do the same thing with empty(), everything is ok:

php > var_dump(empty(null));
bool(true)


Can anyone explain why I receive an error when I try
isset(null)
?




Update

Thank you all for your answers. I asked this question just to make sense of why
isset()
is behaving differently from
empty()
.

To me, both of them are php functions and both accept a parameter. So, as any other function in php, calling
isset(null)
should be a valid statement. Aren't we passing null as a value to isset() function? So why php consider it as an expression?

Answer

Testing if an expression is "set" doesn't make sense. As per the manual, isset is used to

Determine if a variable is set and is not NULL.

If you want to check if an expression is null, use is_null, or as the error message suggests, null !== expression.

The manual for empty suggests something similar:

Determine whether a variable is considered to be empty.

until you read slightly further down, in the changelog:

5.5.0 empty() now supports expressions, rather than only variables.

Prior to this, empty(null) would have thrown an error along the lines of

Parse error: syntax error, unexpected ')', expecting :: (T_PAAMAYIM_NEKUDOTAYIM) in ... on line ...

Comments