0

Maybe silly question, but I have an array and I would like to create an ArrayIterator but with an offset.

Example, I've the following array :

$fruits = [
  1 => 'banana',
  2 => 'apple',
  3 => 'orange',
  ...
  20 => 'raspberry'
]

My offset is 3.

I want to create an ArrayIterator with the $fruits array and the $offset. How can I do that ? I don't understand the ArrayIterator doc'. There is the OffsetSet() method but I don't understand how it works

4
  • You mean to skip the first x elements in an array, yes? Or what do you mean by offset? Commented May 28, 2021 at 10:51
  • Yes that's it, ignore the first x elements Commented May 28, 2021 at 10:53
  • 1
    How to skip the 1st key in an array loop? (you should be able to change the first given answer to skip the first x elements) Commented May 28, 2021 at 10:54
  • 1
    “Yes that's it, ignore the first x elements” - then you appear to have misunderstood what offsetSet does to begin with. See here for an explanation of what it actually does: geeksforgeeks.org/php-arrayiterator-offsetset-function Commented May 28, 2021 at 10:54

1 Answer 1

1

Either skip while you're looping or use array_splice to create a new array from your offset onwards.

$obj = new ArrayObject( array_slice($fruits, 3) );
$it = $obj->getIterator();
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.