Is it possible to reference a specific element of an anonymous array in PHP?

强颜欢笑 提交于 2019-11-29 14:32:13
deceze

No, direct dereferencing is unfortunately not supported in current versions of PHP, but will apparently come in PHP 5.4.

Also see Terminology question on "dereferencing"?.

Array dereferencing is not available in PHP 5.3 right now, but it will be available in PHP 5.4 (PHP 5.4.0 RC2 is currently available for you to tinker with). In the meantime, you can use end(), reset(), or a helper function to get what you want.

$a = array('a','b','c');
echo reset($a);          // echoes 'a'
echo end($a);            // echoes 'c'
echo dereference($a, 1); // echoes 'b'

function dereference($arr, $key) {
    if(array_key_exists($key, $arr)) {
        return $array[$key];
    } else {
        trigger_error('Undefined index: '.$key); // This would be the standard
        return null;
    }
}

Note that end() and current() will reset the array's internal pointer, so be careful.

For your convenience, if you'll be chaining your dereferences this might come in handy:

function chained_dereference($arr, $keys) {
    foreach($keys as $key) {
        $arr = dereference($arr, $key);
    }

    return $arr;
}

// chained_dereference(debug_backtrace(), array(1, 'function')) = debug_backtrace()[1]['function']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!