PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Using iterator_to_array() in PHP

Note: This article was originally published at Planet PHP on 17 April 7020.
Planet PHP

Someone watching over my shoulder recently had never seen the ubiquitously-useful iterator_to_array() before. I'm sure they weren't alone and since I just typed it again, I thought I'd share a snippet.

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.

Consider for example my code which finds records in a MongoDB database; this returns a MongoCursor object, so when I var_dump() it, all I get is a little output telling me that's what sort of an object it is! Using iterator_to_array(), I can grab an array that I can quickly use to check what I got back:

$people = $db-people-find()-sort(array("created" = -1)); print_r(iterator_to_array($people));

In this case, I know there are only two rows in my database so it is a useful diagnostic tool as I put in the first pieces of a new application. Do be careful though about using this function on potentially large datasets! One of the best things about cursors is precisely that they avoid bringing in everything in one go, in case the data set is too large, so there are times when you won't want to put it all into an array at once. However for the times when you do - now you can :)

Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist. This post was originally published at LornaJane