Coding with Jesse

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

October 20th, 2008

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

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!