Patrique Ouimet
Senior Product Engineer
Wed, Oct 23, 2019 9:36 AM
What is the difference between isset
, empty
, and array_key_exists
? You've likely used them all but have you ever thought about how different they are? Let's run through some scenarios with the same values but using each method and seeing what it evaluates to.
<?php
$_GET['foo'] = 'bar';
var_dump(isset($_GET['foo'])); // TRUE
var_dump(empty($_GET['foo'])); // FALSE
var_dump(array_key_exists('foo', $_GET)); // TRUE
$_GET['foo'] = '';
var_dump(isset($_GET['foo'])); // TRUE
var_dump(empty($_GET['foo'])); // TRUE
var_dump(array_key_exists('foo', $_GET)); // TRUE
$_GET['foo'] = null;
var_dump(isset($_GET['foo'])); // FALSE
var_dump(empty($_GET['foo'])); // TRUE
var_dump(array_key_exists('foo', $_GET)); // TRUE
$_GET['foo'] = [];
var_dump(isset($_GET['foo'])); // TRUE
var_dump(empty($_GET['foo'])); // TRUE
var_dump(array_key_exists('foo', $_GET)); // TRUE
unset($_GET['foo']);
var_dump(isset($_GET['foo'])); // FALSE
var_dump(empty($_GET['foo'])); // TRUE
var_dump(array_key_exists('foo', $_GET)); // FALSE
<?php
$_GET['foo'] = 0;
var_dump(isset($_GET['foo'])); // TRUE
var_dump(empty($_GET['foo'])); // TRUE
var_dump(array_key_exists('foo', $_GET)); // TRUE
$_GET['foo'] = '0';
var_dump(isset($_GET['foo'])); // TRUE
var_dump(empty($_GET['foo'])); // TRUE
var_dump(array_key_exists('foo', $_GET)); // TRUE
/*
NOTE: the above two scenarios are usually common with radio buttons where the values
are true (1) or false (0)
*/
$_GET['foo'] = '01';
var_dump(isset($_GET['foo'])); // TRUE
var_dump(empty($_GET['foo'])); // FALSE
var_dump(array_key_exists('foo', $_GET)); // TRUE
// test against non-existent variable
var_dump(isset($bar)); // FALSE
var_dump(empty($bar)); // TRUE
var_dump(array_key_exists('foo', $bar)); // PHP Notice: Undefined variable $bar
// test against a value without variable
var_dump(isset([])); // PHP Parse error: Syntax error, unexpected ')', expecting T_PAAMAYIM_NEKUDOTAYIM
var_dump(empty([])); // TRUE
var_dump(array_key_exists('foo', [])); // FALSE
When using isset
, you can add as many variables as you like and it will not throw an exception even if the array key or object property doesn't exist
<?php
$foo = [];
var_dump(isset($foo->bar, $foo->bar['baz'])); // FALSE
See the great article by Liam Hammett for a more detailed explanation on isset
A Look At PHP’s isset()