PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Lorna Mitchell's Blog: Using iterator_to_array() in PHP

Note: This article was originally published at PHPDeveloper on 17 April 7352.
PHPDeveloper

Lorna Mitchell has a new post to her blog today showing off a lesser-known but very useful function included in PHP - the iterator_to_array function, used to translate things that implement Traversable into arrays.

Someone watching over my shoulder recently had never seen the ubiquitously-useful iterator_to_array() before. [...] Mostly I find this useful when I'm working with collections of data as these often present themselves as an object that you can foreach() over, but you can't dump it directly. If the object in question implements the Traversable interface, you can instead pass it into iterator_to_array to get the data as an array.

She includes a brief snippet of code showing it in use - transforming the results from a MongoDB cursor object back into an array.