Skip to content

Instantly share code, notes, and snippets.

@johnbocook
Forked from juampynr/isset_and_empty.md
Last active August 29, 2015 14:23
Show Gist options
  • Save johnbocook/35f70e977400d76d80f2 to your computer and use it in GitHub Desktop.
Save johnbocook/35f70e977400d76d80f2 to your computer and use it in GitHub Desktop.
Isset and Empty

When dealing with arrays in PHP, checking for an index like if ($a['foo']) throws a PHP warning.

There are two ways to avoid these warnings: one is using isset(), which checks the existance of an array index. The second one is empty(), which not only checks for the existence of the array index, but also that the value that contains is not empty (not NULL, 0, '' or FALSE).

Here are some console examples:

juampy@juampybox $ php -a
php > $a = array('foo' => 'asdfasd');
php > 

Accessing an existing array index is OK:

php > var_dump($a['foo']);
string(7) "asdfasd"

Accessing a non-existent array index throws a warning:

php > var_dump($a['asdfasdfadf']);
PHP Notice:  Undefined index: asdfasdfadf in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0

Notice: Undefined index: asdfasdfadf in php shell code on line 1

Call Stack:
   43.3103     228984   1. {main}() php shell code:0

NULL

isset() checks for the existence of an array index protecting us from warnings:

php > var_dump(isset($a['asdfasdfadf']));
bool(false)

empty() checks for the existence of the index and, if it exists, checks its value:

php > var_dump(empty($a['asdfasdfadf']));
bool(true)

Having an array index with an empty value shows the difference between isset() and empty():

php > var_dump($a);
array(2) {
  'foo' => string(7) "asdfasd"
  'bar' => string(0) ""
}
php > $a['bar'] ='';
php > var_dump(isset($a['bar']));
bool(true)
php > var_dump(empty($a['bar']));
bool(true)
php > var_dump(empty($a['asdfasdfadf']));
bool(true)
php > var_dump(empty($a['foo']));
bool(false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment