In Python I can use "get" method to get value from an dictionary without error.
a = {1: "a", 2: "b"}
a[3] # error
a.get(3, "") # I got empty string.
So I search for a common/base function that do this:
function GetItem($Arr, $Key, $Default){
$res = '';
if (array_key_exists($Key, $Arr)) {
$res = $Arr[$Key];
} else {
$res = $Default;
}
return $res;
}
Have same function basicly in PHP as in Python?
Thanks: dd
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;
}
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