Stupid PHP Tricks: Accumulate nested arrays

I ran into this today while I was dealing with this type of data structure:

$data = array(array('foo', 123),
              array('bar', 456),
              array('qux', 789));

This nested structure has each (key,val) pair as an array inside another array. It’s quite common in Lisp and Python, but not seen very often in PHP, since it’s more concisely expressed as an associative array.

I needed to map a function across all the keys and values in this structure, then produce an associative array. I discovered this somewhat unusual solution:

$keys = $vals = array();
foreach ($data as $pair) {
    list($keys[], $vals[]) = $pair;
}

So what happens is that list appends each new key or value to the appropriate array, leaving me with two flat arrays which I can then array_map() over, finally using array_combine() to produce my final output.

2009/04/08
Previously On Atomized:

Participate