Reputation: 482
I have an array $myarray
like:
Array (
[45] => stdClass Object (
[id] => 45
[response_id] => 2
[question_id] => 1
[choice_id] => 2
)
[46] => stdClass Object (
[id] => 46
[response_id] => 2
[question_id] => 2
[choice_id] => 4
)
...
)
How can I reference the positions of this array? For instance getting the first, second, . . . position of the array.
The only way that seems to work is if I explicitly say
$myarray[45]->choice_id
But I don't always know the numbers and I want to reference the positions. Is there a way to reference the first position as:
$myarray[0]->choice_id
Thanks
Upvotes: 0
Views: 70
Reputation: 41810
In this case it seems like you might as well reindex the array with array_values
. Since the key is the same value as the id property in each of the inner objects you won't be losing any data.
But in general if you want to pick arbitrary positions in the array while preserving its keys, one way is to construct an iterator with it. For example:
$iterator = new ArrayIterator($array);
$iterator->seek(2); // go to position 2 (regardless of key)
$value = $iterator->current();
Of course, if you specifically want the first item, the easiest way is $value = reset($array);
Upvotes: 2