I have an object that implements the ArrayableInterface (BTW, it’s from Laravel’s Eloquent ORM).
This object is $articles. So naturally, I can do this:
foreach ($articles as $article)
echo $article->title . "<br/>";
But I can’t do this:
shuffle($articles);
I get the shuffle() expects parameter 1 to be array, object given warning.
No, it’s not a bug.
PHP 5 allows you to use
foreach()to loop through objects that aren’t arrays. These objects are calledIterators.Unfortunately, the old array-based functions, like
shuffle()cannot process Iterators.The main reason for this is that an Iterator may not even be sortable — for example, you can have iterators that read directly from a file or a URL, and read a new line of data each time the
foreach()loop cycles. This clearly can’t be sorted because it’s read during theforeach()process.You can convert an Iterator into an array, using the cleverly named
iterator_to_array()function. However, this may be a bad idea if you don’t know how much data the iterator is going to process, as you may find it uses a lot of memory.Some iterators may provide methods within the iterator object itself for sorting or filtering the data. If so, this is a better solution than trying to sort it as an array.
If you’re working with an ORM, then this implies that your Iterator object is reading data from a DB. In this case, sorting it via the DB query (ie
ORDER BYor whatever methods the ORM provides to do that) would probably be a better solution than sorting the data in PHP.