Skip to content

Instantly share code, notes, and snippets.

@midnai
Created May 14, 2015 04:06
Show Gist options
  • Save midnai/fa73cb1e9c2e536768a5 to your computer and use it in GitHub Desktop.
Save midnai/fa73cb1e9c2e536768a5 to your computer and use it in GitHub Desktop.
Using PHP's empty() Instead of isset() and count()
//Work with data arrays in PHP
//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 )
);
//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 (count($data['text'])) {
// do something with $data['text']
}
//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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment