Don't forget the function isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does. So all above answer don't correct work with NULL element in array. You can check my edit answer for this situation. For example we had some array:
$test = array(NULL,'',0,false,'0');
If we use (from answer above in this topic) function:
function ifsetor(&$value, $default = null) {
return isset($value) ? $value : $default;
}
and try to get array data:
echo '---------------------';
var_dump($test);
echo 'Array count : '.count($test).'<br>';
echo '---------------------';
var_dump(ifsetor($test[0], 'Key not exists'));
var_dump(ifsetor($test[1],'Key not exists'));
var_dump(ifsetor($test[2],'Key not exists'));
var_dump(ifsetor($test[3], 'Key not exists'));
var_dump(ifsetor($test[4],'Key not exists'));
var_dump(ifsetor($test1[5],'Key not exists'));
function ifsetor(&$value, $default = null) {
return isset($value) ? $value : $default;
}
our result be:
---------------------
array (size=5)
0 => null
1 => string '' (length=0)
2 => int 0
3 => boolean false
4 => string '0' (length=1)
Array count : 5
---------------------
string 'Key not exists' (length=9) //But value in this key of array - NULL! and key exists
string '' (length=0)
int 0
boolean false
string '0' (length=1)
string 'Key not exists' (length=9)
So we can check it use isset and array_key_exists together. Don't forget check this is array or not;
echo '---------------------';
var_dump($test);
echo 'Array count : '.count($test).'<br>';
echo '---------------------';
var_dump(array_get($test, 0, 'Key not exists'));
var_dump(array_get($test, 1,'Key not exists'));
var_dump(array_get($test, 2,'Key not exists'));
var_dump(array_get($test, 3, 'Key not exists'));
var_dump(array_get($test, 4,'Key not exists'));
var_dump(array_get($test, 5,'Key not exists')); //Key not exists
var_dump(array_get($test1, 5,'Key not exists')); //This is not array
function array_get($arr, $key, $default=null) {
if(is_array($arr)){
return isset($arr[$key]) || array_key_exists($key, $arr)
? $arr[$key]
: $default;
}else{
return 'No array given';
}
}
Now the answer is correct:
---------------------
array (size=5)
0 => null
1 => string '' (length=0)
2 => int 0
3 => boolean false
4 => string '0' (length=1)
Array count : 5
---------------------
null //Perfect - key exists!
string '' (length=0)
int 0
boolean false
string '0' (length=1)
string 'No array given' (length=14)
string 'Key not exists' (length=14)