Kategorien
PHP

empty vs. isset vs. array_key_exists

Ich zitier hier einfach mal. Hab ich nämlich nicht gewusst.

The problem is that there are situations where isset() and empty() are
not appropriate checks. For instance, try this:

$test = array('foo' => null);
echo ((isset($test['foo'])) ? 'true' : 'false'); // echoes 'false'!

What about empty()?

$test = array('foo' => null);
echo ((empty($test['foo'])) ? 'true' : 'false'); // echoes 'true'
echo ((empty($test['bar'])) ? 'true' : 'false'); // also echoes 'true'!

What does that mean? It means that if you want to test for the presence
of a key, you can’t rely on isset() *or* empty()! array_key_exists() is
the only way to reliably verify that the key is present in the array.

$test = array('foo' => null);
echo (array_key_exists('foo', $test) ? 'true' : 'false'); // echoes 'true'
echo (array_key_exists('bar', $test) ? 'true' : 'false'); // echoes 'false'

Quote von Matthew Weier O’Phinney, Zend Framework Developer