Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: get array value as in Python?

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

like image 714
durumdara Avatar asked Mar 21 '12 15:03

durumdara


1 Answers

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 NULLs in the array, you must use array_key_exists() instead.

function getItem($array, $key, $default = "") {
  return array_key_exists($key, $array) ? $array[$key] : $default;
}
like image 87
Michael Berkowski Avatar answered Oct 12 '22 20:10

Michael Berkowski