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
}
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
}
See: http://us3.php.net/array_key_exists
isset()
does not returnTRUE
for array keys that correspond to aNULL
value, whilearray_key_exists()
does.
To expand on Mantas's excellent answer, which describes the behavioural difference of the code:
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.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 )
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.