Skip to content

Instantly share code, notes, and snippets.

@danreb
Forked from juampynr/isset_and_empty.md
Created October 30, 2013 23:45
Show Gist options
  • Save danreb/7242254 to your computer and use it in GitHub Desktop.
Save danreb/7242254 to your computer and use it in GitHub Desktop.
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:
```bash
juampy@juampybox $ php -a
php > $a = array('foo' => 'asdfasd');
php >
```
Accessing an existing array index is OK:
```bash
php > var_dump($a['foo']);
string(7) "asdfasd"
```
Accessing a non-existent array index throws a warning:
```bash
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:
```bash
php > var_dump(isset($a['asdfasdfadf']));
bool(false)
```
empty() checks for the existence of the index and, if it exists, checks its value:
```bash
php > var_dump(empty($a['asdfasdfadf']));
bool(true)
```
Having an array index with an empty value shows the difference between isset() and empty():
```bash
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