How to check if a variable is undefined in PHP?
Which methods are available in PHP to check if a variable or an array key is defined?
Check with isset():
Isset() can be used to check whether a variable has already been defined.
<?php $a = 50; $b = 0; $str = ''; var_dump(isset($a)); // true var_dump(isset($b)); // true var_dump(isset($str)); // true var_dump(isset($x)); // false ?>
Output:
bool(true) bool(true) bool(true) bool(false)[st_adsense]
Isset() applied to arrays:
Isset() is often used on arrays to check whether the value for a certain key exists:
<?php $person = array('alex'=>25, 'emily'=>12, 'bob'=>30); if (isset($person['alex'])) { echo($person['alex']); } else { echo('Alex\'s age is unknown.'); } ?>
Output:
25
Empty() and arrays:
isset() has a disadvantage: If a variable is assigned the value NULL, isset() returns false, regardless of whether the value of a variable ($var) or an array key ($var[‘key’]) is tested. This problem can be avoided by using! Empty() instead of isset().
<?php $a = 50; $b = null; $c = array('one'=>1, 'two'=>null); var_dump( isset($a) ); // true var_dump( isset($b) ); // false var_dump( isset($c['one']) ); // true var_dump( isset($c['two']) ); // false echo("\n\n"); var_dump( !empty($a) ); // true var_dump( !empty($b) ); // false var_dump( !empty($c['one']) ); // true var_dump( !empty($c['two']) ); // false ?>
Output:
bool(true) bool(false) bool(true) bool(false) bool(true) bool(false) bool(true) bool(false)[st_adsense]
Isset() vs empty() vs array_key_exists() for arrays :
Also empty() has its own disadvantages: All false-like values are considered empty and therefore empty() returns true for them. These values are in detail: (bool)false, (int)0, (float)0.0, (string)””, (string) “0” and NULL. In order to “circumvent” this problem, the function array_key_exists() can be used. This function expects the name of the key to be checked and the array to be checked. If the key is defined in the array – no matter which value – true is returned, otherwise false.
<?php $arr = array('A'=>1, 'B'=>null, 'C'=>0); echo("isset():\n"); var_dump(isset($arr['A'])); // true var_dump(isset($arr['B'])); // false var_dump(isset($arr['C'])); // true var_dump(isset($arr['D'])); // false echo("\nempty():\n"); var_dump(!empty($arr['A'])); // true var_dump(!empty($arr['B'])); // false var_dump(!empty($arr['C'])); // false var_dump(!empty($arr['D'])); // false echo("\narray_key_exists():\n"); var_dump(array_key_exists('A', $arr)); // true var_dump(array_key_exists('B', $arr)); // true var_dump(array_key_exists('C', $arr)); // true var_dump(array_key_exists('D', $arr)); // false ?>
Output:
isset(): bool(true) bool(false) bool(true) bool(false) empty(): bool(true) bool(false) bool(false) bool(false) array_key_exists(): bool(true) bool(true) bool(true) bool(false)[st_adsense]