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

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
durumdara
  • 3,411
  • 4
  • 43
  • 71
  • 1
    why you need a function to get the value using a key of the array. $a['key'] what is wrong with this – zod Mar 21 '12 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. – Justin ᚅᚔᚈᚄᚒᚔ Mar 21 '12 at 16:04

5 Answers5

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;
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 2
    I made another helper function which is simpler and needs fewer arguments: http://stackoverflow.com/a/25205195/1890285 – stepmuel Aug 08 '14 at 14:01
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;
}
Justin ᚅᚔᚈᚄᚒᚔ
  • 15,081
  • 7
  • 52
  • 64
0

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

$Arr[$Key] ?? $default

Toskan
  • 13,911
  • 14
  • 95
  • 185
0

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

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

NeeL
  • 720
  • 6
  • 20
0

Yes. or

function GetItem($Arr, $Key, $Default) {
  return array_key_exists($Key, $Arr)
      ? $Arr[$Key]
      : $Default;
}
Borodin
  • 126,100
  • 9
  • 70
  • 144