Filter an array of objects

Last modified date

Comments: 0

Quite often I might have an array of objects, be it from a db query or some json object, and I want to filter that list in a particular way.  Lots of times I would find myself doing the same old thing; creating a new array, looping and looping until all I had left was what matched my filter.

I’m sure you’ve been there and done it a thousand times, too.

Well, this little function should help that task out a lot!

Say I had an array of people objects and wanted only those people who’s name was Bob and was aged 35, I could do something as simple as:

[php]$filtered = ofilter($items, [‘name’ => ‘Bob’, ‘age’ => 35]);[/php]

Or maybe something a little tricker; I wanted to get anyone whose age was between 18 and 35 (inclusive):

[php]$filtered = ofilter($items, [‘age’ => function($age) { return ($age >= 18 && $age < = 35); }]);[/php]

Pretty easy, eh?

Here’s the code – it’s a GitHub gist, so feel free to fork and improve!

Share

Leave a Reply

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