14

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
}
Jhonathan H.
  • 2,734
  • 1
  • 19
  • 28
Rakesh K
  • 692
  • 4
  • 13
  • 26

3 Answers3

21

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.

Florent
  • 12,310
  • 10
  • 49
  • 58
Mantas
  • 4,259
  • 2
  • 27
  • 32
10

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 ) 
reformed
  • 4,505
  • 11
  • 62
  • 88
Rob Baillie
  • 3,436
  • 2
  • 20
  • 34
0

In my opinion if you will definitely go deep through of using arrays

i suggest using array_key_exists() just accompanied it with some usefull array functions

just like array_filter() . Also the fact that array functions are created is because of arrays and ease of use isset() would be having his best place to use as e.g checking variable existence. . OR else theres a lot of more functions to explore for arrays use out there.

But after all it would be truly depends on you what result are you trying to expect either you want an array() with NULL or not.

Jhonathan H.
  • 2,734
  • 1
  • 19
  • 28