I find myself doing this a lot:
if (isset($myarray['foo']) && $myarray['foo'])) { // do something }
But I thought there had to be a better way, and one that would not throw undefined errors. A quick google search came up with a few good hits, include the PHP manual page for empty().
The manual says that when using empty(), no warnings are thrown when a variable is not set. It will return true in the following cases:
“” (an empty string)
0 (0 as an integer)
“0″ (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Keep in mind that an object with no properties is not considered empty().
Now, we can make our code a bit more beautiful:
if (!empty($myarray['foo'])) { // do something }
I’ve known about empty() for a long time, but for some reason always seemed to choose isset() over empty(), even in cases like this.




Bear in mind that you often can’t use empty on the response from and object method unline isset.
For example in symfony if you had a blog object you can do:
if(isset($blog->getTitle()) && $blog->getTitle() != “”){}
But you cannot do if(empty($blog->getTitle())){}
By Harry Walter on Jul 11, 2009
And then there’s array_key_exists() sigh…
By Jon Williams on Jul 11, 2009
To expand upon what Harry Walter said, empty() can’t be used on the value returned by any function, be it an object method or a regular function. empty() has some funky behavior because it’s part of the PHP interpreter and is a language component rather than a function, just like echo.
By Andrew Noyes on Jul 27, 2009