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
}
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 )
See: http://us3.php.net/array_key_exists
isset()
does not returnTRUE
for array keys that correspond to aNULL
value, whilearray_key_exists()
does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With