Using iterator_to_array() in 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 :)

10 thoughts on “Using iterator_to_array() in PHP

  1. Great info Lorna. Another thing to note about iterator_to_array. If you have a RecursiveIterator, on possibly a multi-dimensional array, it will flatten your data. Just something to keep in mind.

  2. Pingback: Lorna Mitchell’s Blog: Using iterator_to_array() in PHP | Scripting4You Blog

  3. Pingback: Using iterator_to_array() in PHP | LornaJane | Bloc notes PHP | Scoop.it

  4. Here is a class method I use to convert a SimpleXMLIterator for a structure of arbitrary depth to an array:

    [code]
    itToArray($a);
    }
    }

    return $array;
    }
    }
    ?>
    [/code]

    Feel free to delete my obvious post-before-I-read comment without code tags ;)

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.