11

I've started to learn PHP SPL from ArrayIterators and I'd like to know what are the benefits of using SPL ArrayObject, ArrayIterator, RecursiveArrayIterator instead of regular arrays?

a) I've heard that loops using SPL iterators will reduce memory usage (but why?). I don't really know to believe this or no because I don't understand how can it reduce memory usage.

b) Talking about RecursiveArrayIterator we can say that sometimes it could save some lines of code (we're using one foreach construction instead of 2+ (depends on array dimension)).

Probably, my questions could seem to be very easy for somebody, but there are too little information/documentation about SPL.

Thank you

1

1 Answer 1

8

The primary benefit you're looking at efficient data access mostly in the area of readability. This way you can use object just like an array in a foreach so a closer interaction with PHP.

a) The way you reduce memory usage is by not making a copy of the array but if done properly in the engine then it should be a new reference until the array is modified then it's actually copied.

b) Essentially

A good example of this would be the SimpleXML extension. The PHP/XML object you're interacting with also acts like an array which makes it efficient to use because you can just foreach or access one of the elements within the list. You don't have to grab an array from the object and then iterate over and do something else with it if you want the tag name or an attribute.

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.