Archive for 2012

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! 🙂

Zend Job Queue article for PHPMaster.com

Last month I learned about great opportunity to write for PHPMaster.com and contacted their managing editor.
It worked out very well and a blog post I had in mind for while turned into a great article. 🙂

Any feedback is welcomed: Scheduling with Zend Job Queue.

MongoDB Atlanta

MongoDB conference is going to happen in Atlanta again this year. I’ve enjoyed MongoATL 2011 and already have made plans to attend this year too. Although the conference is still at “call for proposals” stage, I am sure there will be covered interesting topics since MongoDB popularity has grown significantly.

It is probably a good idea to follow event details on the MongoDB Atlanta 2012 official page. However location stays the same (GTRI Conference Center) and date is already known – April, 20th.

« Previous Page