Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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


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

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

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

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

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']));
php > var_dump(empty($a['bar']));
php > var_dump(empty($a['asdfasdfadf']));
php > var_dump(empty($a['foo']));

This comment has been minimized.

Copy link

@rodricels rodricels commented Nov 28, 2013

Una tabla que mantengo siempre impresa cerca de mi escritorio:

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