Do you really need to check for both isset() and empty() at the same time?

  1. Comments (3)

The below code can be seen too often to be ignored on this site dedicated to treating PHP delusions, being one of the most frequent cases:

 if (isset($someVar) && !empty($someVar)) 

Being unfamiliar with PHP's loose typing, learners often mistake if(empty($someVar) with just if($someVar), thinking empty() will check for the empty-like values (like an empty string, zero number and such), whereas in PHP for this purpose could be used the variable itself: thanks to the type juggling, when using in the condition, it will be cast to the boolean value, which will effectively check for the "emptiness" already, making a dedicated function quite useless.

So you can tell that the above snippet could be shortened to

 if (isset($someVar) && $someVar

but the most funny part is... this code being the exact definition for !empty(), because the very purpose of this function is to tell whether a variable is either not set or "empty".

So now you can tell that checking for both isset() and empty() is an obvious overkill and empty() alone is more than enough, making the initial condition as simple as

 if (!empty($someVar)) 

On the other hand, people often use empty() against a variable that deliberately exists. It would be overkill again, because for the already declared variable, if(!empty($var)) would be exactly the same as just if($var) which is way more clean and readable. Same goes for the expressions as well.


Related articles: