PHP: array_filter() with arguments
Recently I have been using a lot of array related functions. Especially array_count_values() function came in handy. It really saved me a lot of sweat while cracking some puzzles.
Anyway the other day I got a chance to play with array_filter() function. At the first look this function works just fine and required callback function is extremely easy to write. Until one realizes it would be great to have an extra parameter the same way array_walk() does.
// some array $a = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // custom multiplier $p = 5; function walk(&$value, $key, $m) { $value = $value * $m; } // multiply each element of the array by $p array_walk($a, 'walk', $p); print_r($a); |
So with array_walk() it is possible simply to add optional third parameter ($p in the example above) and it will just work. However array_filter() does not allow that third parameter – there are just two of them…
What I did not take into account that callback function “can not only be simple functions, but also object methods, including static class methods”. As result this solves the issue in the way shown below.
// some array $a = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // threshold to filter array elements $p = 5; // method of this class can be uses as a callback function class Filter { private $threshold; function __construct($threshold) { $this->threshold = $threshold; } function isLower($i) { return $i < $this->threshold; } } $r = array_filter($a, array(new Filter($p), 'isLower')); print_r($r); |
Although the code above gets the job done, it feels like it is too much effort for an “extra parameter”. And this is when anonymous function and closure come helpful to provide one-line solution which I always appreciate:
$a = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); $p = 5; $r = array_filter($a, function($i) use ($p) { return $i < $p; }); print_r($r); |
Voilà – such an elegant way to solve the problem! 🙂
Brilliant – I thought I knew PHP 5 pretty well, but now I learnt it has closures.