15

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

2
  • 1
    why you need a function to get the value using a key of the array. $a['key'] what is wrong with this Commented Mar 21, 2012 at 15:28
  • 1
    @zod: If the key doesn't exist, you get a PHP error. Using a function like the ones in the answers below allows you to get a default value instead of an error message. Commented Mar 21, 2012 at 16:04

5 Answers 5

10

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;
}
1
2

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;
}
0

There is no base function to do that in my mind.

Your GetItem is a good way to do what you wanna do :)

0

Yes. or

function GetItem($Arr, $Key, $Default) {
  return array_key_exists($Key, $Arr)
      ? $Arr[$Key]
      : $Default;
}
0

php7 is out for a long time now so you can do

$Arr[$Key] ?? $default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.