Do you really need to check for both isset() and empty() at the same time?
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 such as an empty string, a zero and such, whereas in PHP, for this purpose could be used the variable itself: thanks to the type juggling, when used in the conditional operator, any value will be cast to boolean, 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.
An important note: as a matter of fact, both
isset()andempty(), as well as a null coalescing operator often get misused. See an excellent comment from Hayley Watson and also an article I wrote about such a misuse. In a nutshell, you should think twice, whether you want to use such operators, or you want to have your variables more organized and take PHP to warn you about possible issues
Related articles:
- Relative and absolute paths, in the file system and on the web server.
- PHP error reporting
- Do you abuse the null coalescing operator (and isset/empty as well)?
- What's wrong with popular articles telling you that foo is faster than bar?
- Articles
- Numerical strings comparison
- MVC in simpler terms or the structure of a modern web-application
- How to get a single player's rank based on the score
- Why should I use prepared statements if escaping is safe?
- Operator precedence or how does 'or die()' work.
- Do generators really reduce the memory usage?
- How to make Stack Overflow a nice place
- How to debug small PHP programs
- Iterating over array getting look-ahead items along
Comments:
Just to reply to Hayley Watson comment, there are actually some case where it makes sense to check if the variable is defined. Not advocating to put one self in a situation where you'd want to check a variable is defined.
You'd want use isset if unset may have been used earlier, or if you are trying to access a global variable you are not sure it may or not have been defined. Bot are bad practices, but this the world of PHP
Hi mate, I've been seeing a few articles around about PHP_SELF being a problem (unsafe), usually from people not using PDO or any sort of abstraction. Is it safe to redirect using PHP_SELF? Is there a better option that avoids potential XSS?
Hi!
But doing if($var) on variable that doesn't exist will result in a warning, so if I want to check, sayy, I will have to use !empty instead?
Reply:
If you want to check a $_GET or $_POST array key, then you must use isset() (or, strictly speaking - array_ke_exists())
If you want to check a $_GET or $_POST array value, then your best bet is to validate it properly, instead of just checking for being "empty". 0 could be a legit value, but empty won't let it through. An array is will cause an error where a string is expected, but empty() won't warn you.
So I wouldn't use empty() for input validation at all.
Are you somehow related to 'Kyle Simpson' the author of You-Dont-Know-JS?
Sometimes reading here I catch my self thinking I'm reading that book but than I see the blue light color theme of the website and i remember that nope, I PHP.
No really joke a part, you should write something similar, like You-Don't Know PHP :P
Reply:
Hello Federico!
Sadly, I am nether acquainted with Kyle Simpson nor with You-Dont-Know-JS book. Actually my knowledge and interest in JS are quite limited. but I am glad there is something similar about this great language.
Thank you for the suggestion, I will definitely think of creating one!
A bit of a digression, because it has nothing to do with empty(), but...
Really, how much of a use case is there for
isset($plainvariable)? Is your function so wildly out of control that you can't keep track of whether your variables have even been initialized or not? That would be the real problem.isset($compositevariable['key']), sure: if you get passed an array, PHP doesn't give you any guarantee it has all the fields you might want to look at (and note that array_key_exists is more strict about what counts as "set").isset($object->field)if there's duck-typing going on. Decoded JSON and such.Oh, maybe you want to see if the variable contains an actual null-type null? You should say so for the sake of self-documenting code:
$plainvariable === nulloris_null($plainvariable). Often, though, passing nulls around a lot is a bit of a code smell (it's short for "I really don't know what value to put in this variable, I shouldn't even be using it to be honest with myself"). If you have to put up with them coming in from outside, check for them as above and move on.But
isset($plainvariable)? You need to step back a bit and ask yourself why.Reply:
Hello Hayley!
Thank you for the excellent addition to the article!
You are absolutely correct, and sadly, not so many people are sharing your concerns. Actually some time ago I wrote a similar rant, but it would be a good idea to add the link here, as well as a link to your comment. So I did!
There are situations when "0"(or maybe 0) is valid. For example user input, i found a solution that includes the trim function: if (isset($_POST['fieldName']) && trim($_POST['fieldName']) !== "") { echo "There's something here!"; }
does this apply to $somevar=array(); Thanks for the effort you have extended to the rest of us.
Reply:
Hello Bob!
An empty array considered a FALSE-like variable in PHP. You may find these tables useful: https://www.php.net/manual/en/types.comparisons.php
Thanks for your articles and examples!
You seem to have a typo in this line:
There is one right parenthesis too much.
Reply:
Hello Petko!
Thank you very much, indeed it was a typo. Fixed!
And if the variable is not set, will not it generate a notice?
Reply:
Hello Everton!
Nope, it will not.