To expand on Mantas's excellent answer, which describes the behavioural difference of the code:
- Use array_key_exists if you want to find out if that key exists in the array, regardless of whether it contains a value or not.
- Use isset if you want to find out if the key exists in an array and has a value in it of meaning. Note that
isset
will return false for NULL
values.
The semantic difference described above leads to the behavioural difference described by Mantas.
The following code:
$aTestArray = array();
echo "Before key is created\r\n";
echo "isset:\r\n";
var_dump( isset( $aTestArray['TestKey'] ) );
echo "array_key_exists:\r\n";
var_dump( array_key_exists( 'TestKey', $aTestArray ) );
echo "\r\n";
$aTestArray['TestKey'] = NULL;
echo "Key is created, but set to NULL\r\n";
echo "isset:\r\n";
var_dump( isset( $aTestArray['TestKey'] ) );
echo "array_key_exists:\r\n";
var_dump( array_key_exists( 'TestKey', $aTestArray ) );
echo "\r\n";
$aTestArray['TestKey'] = 0;
echo "Key is created, and set to 0 (zero)\r\n";
echo "isset:\r\n";
var_dump( isset( $aTestArray['TestKey'] ) );
echo "array_key_exists:\r\n";
var_dump( array_key_exists( 'TestKey', $aTestArray ) );
echo "\r\n";
Outputs:
Before key is created
isset:
bool(false)
array_key_exists:
bool(false)
Key is created, but set to NULL
isset:
bool(false)
array_key_exists:
bool(true)
Key is created, and set to 0 (zero)
isset:
bool(true)
array_key_exists:
bool(true)
A side-effect is that a key that returns "false" from isset may still be included as key in a for each loop, as in
foreach( $array as $key => value )