Filter an array of objects

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:

$filtered = ofilter($items, ['name' => 'Bob', 'age' => 35]);

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

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

Pretty easy, eh?

Here’s the code – it’s a GitHub gist, so feel free to fork and improve!
Continue reading “Filter an array of objects”

Did you like this? Share it:

Shorten urls automatically with a Zend Framework filter

I think we can all agree that URL shortening services are great and are very handy to tidy up those long and obnoxious links. However, a lot of the time people simply forget to use them, or often don’t know about them in the first place. I’ve noticed this in a blog system I wrote using Zend Framework. On one hand I love that people post messages, but on the other it annoys me that they may supply a link that is so long it breaks the formatting of the page, or looks just plain ugly.

So what are my options? I could train everyone who posts blogs on the system to use a url shortening service or I could manually tweak all the links myself. As solutions they are not very practical at all; I don’t have the time to change any/all links myself, and I certainly don’t have enough patience to train everyone! So an automatic way of doing things is needed, and the filtering in Zend Framework comes to the rescue!

Continue reading “Shorten urls automatically with a Zend Framework filter”

Did you like this? Share it: