0

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

1
  • 5
    You could use array_values to reset the keys with the usual zero indexed sequence. Commented Aug 9, 2019 at 21:58

1 Answer 1

2

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

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

Comments

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.