PHP: get array value as in Python?
isset()
is typically faster than array_key_exists()
. The parameter $default
is initialized to an empty string if omitted.
function getItem($array, $key, $default = "") {
return isset($array[$key]) ? $array[$key] : $default;
}
// Call as
$array = array("abc" => 123, "def" => 455);
echo getItem($array, "xyz", "not here");
// "not here"
However, if an array key exists but has a NULL value, isset()
won't behave the way you expect, as it will treat the NULL
as though it doesn't exist and return $default
. If you expect NULL
s in the array, you must use array_key_exists()
instead.
function getItem($array, $key, $default = "") {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
Not quite. This should behave the same.
function GetItem($Arr, $Key, $Default = ''){
if (array_key_exists($Key, $Arr)) {
$res = $Arr[$Key];
} else {
$res = $Default;
}
return $res;
}
The first line in your function is useless, as every code path results in $res
being overwritten. The trick is to make the $Default
parameter optional as above.
Keep in mind that using array_key_exists()
can cause significant slowdowns, especially on large arrays. An alternative:
function GetItem($Arr, $Key, $Default = '') {
return isset($Arr[$Key]) ? $Arr[$Key] : $Default;
}