Count “truthy” values in a 2d array

From the PHP array_filter documentation: //This function filters an array and remove all null values recursively. <?php function array_filter_recursive($input) { foreach ($input as &$value) { if (is_array($value)) { $value = array_filter_recursive($value); } } return array_filter($input); } ?> //Or with callback parameter (not tested) : <?php function array_filter_recursive($input, $callback = null) { foreach ($input as &$value) … Read more

Keep array rows where a column value is found in a second flat array

This whole task can be accomplished with just one slick, native function call — array_uintersect(). Because the two compared parameters in the custom callback may come either input array, try to access from the id column and if there isn’t one declared, then fallback to the parameter’s value. Under the hood, this function performs sorting … Read more

How to run array_filter recursively in a PHP array?

From the PHP array_filter documentation: //This function filters an array and remove all null values recursively. <?php function array_filter_recursive($input) { foreach ($input as &$value) { if (is_array($value)) { $value = array_filter_recursive($value); } } return array_filter($input); } ?> //Or with callback parameter (not tested) : <?php function array_filter_recursive($input, $callback = null) { foreach ($input as &$value) … Read more

Remove all elements from array that do not start with a certain string

Functional approach: $array = array_filter($array, function($key) { return strpos($key, ‘foo-‘) === 0; }, ARRAY_FILTER_USE_KEY); Procedural approach: $only_foo = array(); foreach ($array as $key => $value) { if (strpos($key, ‘foo-‘) === 0) { $only_foo[$key] = $value; } } Procedural approach using objects: $i = new ArrayIterator($array); $only_foo = array(); while ($i->valid()) { if (strpos($i->key(), ‘foo-‘) === … Read more