Coding with Jesse

Using PHP's empty() Instead of isset() and count()

I often work with data arrays in PHP as a way to pass information around or store information in sessions. When you work with these, you can't always assume that all properties are defined. I had some conditional logic code in PHP that was only supposed to execute if an array contained any values:

$data = array(
   'text' => array( 'hello', 'world' ),
   'numbers' => array( 43, 2, 55 )
);

if (count($data['text'])) {
   // do something with $data['text']
}

But then I was in a situation where $data['text'] may or may not be defined. So I was going to update my if statement like so:

if (isset($data['text']) && count($data['text'])) {
   // do something
}

But that looks kind of messy. I don't really like isset() but it is a necessary evil to avoid "Undefined" errors. Or is it?

if (!empty($data['text'])) {
   // do something
}

empty() to the rescue - it returns true if $data['text'] is undefined, or if it is an empty array, or if it is false or null or 0. So !empty() is what I'm really trying to determine, and it works great.

For more info, see: empty() at PHP.net.

Published on October 20th, 2008. © Jesse Skinner

About the author

Jesse Skinner

I'm Jesse Skinner. I'm a self-employed web developer. I love writing code, and writing about writing code. Sometimes I make videos too. Feel free to email me if you have any questions or comments, or just want to share your story or something you're excited about.