Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isset vs array_key_exists [duplicate]

Tags:

arrays

php

Where is isset or array_key_exist suitable to use ?

In my case both are working.

if( isset( $array['index'] ) {
   //Do something
}    


if( array_key_exists( 'index', $array ) {
   //Do something
}
like image 786
Rakesh K Avatar asked Nov 21 '13 08:11

Rakesh K


2 Answers

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 ) 
like image 140
Rob Baillie Avatar answered Sep 20 '22 08:09

Rob Baillie


See: http://us3.php.net/array_key_exists

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

like image 42
Mantas Avatar answered Sep 19 '22 08:09

Mantas