PHP: Fastest way to handle undefined array key

后端 未结 8 1643
梦如初夏
梦如初夏 2020-12-08 07:13

in a very tight loop I need to access tenthousands of values in an array containing millions of elements. The key can be undefinied: In that case it shall be legal to return

8条回答
  •  独厮守ぢ
    2020-12-08 07:36

    I prefer using the isset function instead of escaping the error. I made a function to check the key exists and if not returns a default value, in the case of nested arrays you just need to add the other keys in order:

    Nested array lookup:

    /**
     * Lookup array value.
     *
     * @param array $array
     * @param array $keys
     * @param $defaultValue
     */
    public static function array_key_lookup($array, $keys, $defaultValue)
    {
        $value = $array;
        foreach ($keys as $key) {
            if (isset($value[$key])) {
                $value = $value[$key];
            } else {
                $value = $defaultValue;
                break;
            }
        }
    
        return $value;
    }
    

    Usage example:

    $array = [
        'key1' => 'value1',
        'key2' => 'value2',
        'key3' => [
            'key3a' => 'value3a',
            'key3b' => 'value3b'
        ]
    ];
    
    array_key_lookup($array, ['key3', 'key3a'], 'default')
    'value3a'
    
    array_key_lookup($array, ['key2', 'key2a'], 'default')
    'default'
    
    array_key_lookup($array, ['key2'], 'default')
    'value2'
    
    array_key_lookup($array, ['key5'], 'default')
    'default'
    
    

    Escaping the error:

    $value = @$array[$key1][$key2] ?: $defaultValue;
    

提交回复
热议问题