Take the 2-minute tour ×

I'm trying to figure out why it is that I cannot access the follow array with this statement:


    [d142d425a5487967a914b6579428d64b] => Array
            [product_id] => 253
            [variation_id] => 
            [variation] => 
            [quantity] => 1
            [data] => WC_Product Object
                    [id] => 253
                    [product_custom_fields] => Array
                            [_edit_last] => Array
                                    [0] => 1

                            [_edit_lock] => Array
                                    [0] => 1345655854:1

                            [_thumbnail_id] => Array
                                    [0] => 102

I can, however, access the 'product_id' using the dynamically created array name:


The issue is, I don't know what that dynamic name is going to be on the fly...

share|improve this question
add comment

3 Answers

up vote 0 down vote accepted

Because PHP array are associative therefor you have to access them by key.

But you may use reset($thevar) to get first item.

Or array_values():


Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:

$thevar[ array_keys($thevar)[0]]
share|improve this answer
So I in fact DO need to find out what that Key is in order to navigate it. –  dcolumbus Oct 10 '12 at 19:45
No, you may also use array_values (as I mentioned), but that would create new array. Using reset() should be really the fastest way to do this. –  Vyktor Oct 10 '12 at 19:48
add comment

There are several options for such scenarios.

Manually iterate over the array

You can use reset, next, key and/or each to iterate over the array (perhaps partially).

For example, to grab the first item regardless of key:

$item = reset($thevar);

Reindex the array

Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:

$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed

Iterate with foreach

This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.

foreach($thevar as $item) {
    // do something with $item
share|improve this answer
add comment

If the array key is dynamic you might find the PHP function array_keys() useful.

It will return an array of the keys used in an array. You can then use this to access a particular element in the array.

See here for more:


share|improve this answer
add comment

Your Answer


