defaultdict In PHP

In the little experience I’ve had with programming in Python, I’ve found the defaultdict class to be one of the most useful.

PHP already has a limited version of this feature built in, called autovivification:

$arr = array();
$arr['foo']['bar'] = 1;

print_r( $arr['foo'] );  // Result: Array ( [bar] => 1 )

print_r( $arr['baz'] );  // Result: Undefined index: baz

As you can see, it doesn’t work when accessing an undefined value; when implicitly setting a value, you can only construct arrays.

Fortunately, it’s pretty easy to implement our own version of Python’s defaultdict by using the special ArrayAccess interface (requires PHP >= 5.3.4):

You use it just as if it were a regular associative array:

$counts = new Defaultdict(1);

echo $counts['foo']; // Result: 1

$counts['bar']++;

echo $counts['bar']; // Result: 2

And you can even pass an anonymous function for constructing new default values:

$instances = new Defaultdict( function( $key ) {

	$value = new stdClass;
	$value->id = $key;

	return $value;
} );

print_r( $instances['bar'] );  // Result: stdClass Object ( [id] => bar )

comments powered by Disqus