Access PHP array element with a function?

I'm working on a program that uses PHP's internal array pointers to iterate along a multidimensional array. I need to get an element from the current row, and I've been doing it like so:

$arr[key($arr)]['item']

However, I'd much prefer to use something like:

current($arr)['item'] // invalid syntax

I'm hoping there's a function out there that I've missed in my scan of the documentation that would enable me to access the element like so:

getvalue(current($arr), 'item')

or

current($arr)->getvalue('item')

Any suggestions?


I very much doubt there is such a function, but it's trivial to write

function getvalue($array, $key)
{
  return $array[$key];
}

Edit: As of PHP 5.4, you can index array elements directly from function expressions, current($arr)['item'] .


Have you tried using one of the iterator classes yet? There might be something in there that does exactly what you want. If not, you can likely get what you want by extending the ArrayObject class.


This function might be a bit lenghty but I use it all the time, specially in scenarious like:

if (array_key_exists('user', $_SESSION) === true)
{
    if (array_key_exists('level', $_SESSION['user']) === true)
    {
        $value = $_SESSION['user']['level'];
    }

    else
    {
        $value = 'DEFAULT VALUE IF NOT EXISTS';
    }
}

else
{
    $value = 'DEFAULT VALUE IF NOT EXISTS';
}

Turns to this:

Value($_SESSION, array('user', 'level'), 'DEFAULT VALUE IF NOT EXISTS');

Here is the function:

function Value($array, $key = 0, $default = false)
{
    if (is_array($array) === true)
    {
        if (is_array($key) === true)
        {
            foreach ($key as $value)
            {
                if (array_key_exists($value, $array) === true)
                {
                    $array = $array[$value];
                }

                else
                {
                    return $default;
                }
            }

            return $array;
        }

        else if (array_key_exists($key, $array) === true)
        {
            return $array[$key];
        }
    }

    return $default;
}

PS: You can also use unidimensional arrays, like this:

Value($_SERVER, 'REQUEST_METHOD', 'DEFAULT VALUE IF NOT EXISTS');
链接地址: http://www.djcxy.com/p/69580.html

上一篇: 类可以扩展一个类并实现一个接口

下一篇: 使用函数访问PHP数组元素?