Skip to content

Instantly share code, notes, and snippets.

@juampynr
Last active December 19, 2015 22:48
Show Gist options
  • Save juampynr/6029872 to your computer and use it in GitHub Desktop.
Save juampynr/6029872 to your computer and use it in GitHub Desktop.
PHP isset() and empty() black magic

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)
@rodricels
Copy link

Una tabla que mantengo siempre impresa cerca de mi escritorio: http://www.hackbs.com/wp-content/uploads/2012/08/is_null-empty-unset.jpg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment