Don't let arrays make you loopy!

As a Drupal developer, I spend 90% of my time mucking with PHP arrays. And as much as I love a foreach control structure, PHP provides some nice functions that can get you what you need from an array without having to loop through a huge Drupal Node array.

For example, say I wanted to filter some nodes to see if they were referencing a specific Vocabulary term: The array_filter function can be used to filter out empty values from an array, but it can also be used with a callback function to filter based on whatever specification you want:

Here’s the simple “Filter out empty values” behavior:

'Apple', 2 => NULL, 3 => 1, ); $filtered_array = array_filter($array); print_r($filtered_array); // Returns: Array ( [1] => Apple [3] => 1 ) ?>

But what if we wanted to filter for anything with a specific value?

Apple ) ?>

Dynamically filtering with a closure

As of PHP 5.3, the callback function can also be a “closure”, or anonymous function. This allows for dynamically setting the value for the filter, which is awesome:

Apple ) ?>

Get In Touch

Questions? Comments? We want to know! Drop us a line and let’s start talking.

Learn More
Get In Touch

Related Blog Posts