15

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?

2
  • 2
    You have already found the best solution: $arr[key($arr)]['item'] Commented Dec 28, 2008 at 20:27
  • The getvalue approach would be useful even of single-dimmensional arrays too. It would allow to workaroung the ≤5.3 syntax limitations and allowing to access an element from an array, say returned by a function call, directly within one statement. I’m missing such internal function. Commented May 26, 2015 at 5:28

5 Answers 5

12

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'].

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is probably what I'll end up doing. If you are correct that there is no such function, it's a pretty bad oversight.
1

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.

1 Comment

Just looked at those - it looks like that's just an object oriented way to iterate through the array. The ArrayIterator::current returns the current item, much in the same way the current() function does, which isn't really the problem I was having.
0

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');

Comments

-1

If this does not work, how is your multidimensional array composed? A var_dump() might help.

$subkey = 'B';
$arr = array(
    $subkey => array(
        'AB' => 'A1',
        'AC' => 'A2'
    )
);


echo current($arr[$subkey]);
next($arr[$subkey]);
echo current($arr[$subkey]);

2 Comments

The iteration I'm performing is really only along the primary array. I said "multidimensional" because the corresponding elements of the main array are themselves arrays, but I don't want to iterate over them - I just want to conveniently access them.
How about treating $arr[$subkey] as an array, or $new_arr = array_values($arr[$subkey])? Footnote: what differs between your requested current($arr)['item'] and current($arr['item'])?
-1

I often use

foreach ($arr as $key=>$val) {
   $val['item'] /*$val is the value of the array*/
   $key         /*$key is the key used */
}

instead of

next($arr)/current($arr)

1 Comment

I use that too - for the sake of the question I eliminated the fact that I'm actually going down two sorted arrays looking for differences, and I' m pretty sure foreach doesn't support that kind of access, but I could be wrong. Anyways, thanks for your reply. :)

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.