A better way to combine PHP arrays

September 24, 2014

I recently had a use case where I needed to combine two arrays in PHP…

<?php
$people = ['Bob', 'Frank'];
$ages = [23, 54];

… to end up with an array that looked like this:

<?php
Array
(
    [0] => Array
        (
            [0] => Bob
            [1] => 23
        )

    [1] => Array
        (
            [0] => Frank
            [1] => 54
        )
)

In python, I’d just use the zip function - I wanted something similar in PHP. The solution was to pass null as the first argument to array_map:

<?php
$people = array_map(null, $people, $ages);

For comparison’s sake, here’s how you’d achieve this without using array_map:

<?php
$tmp_people = [];
foreach ($people as $k => $v) {
    $tmp_people[] = [$v, $ages[$k]];
}
$people = $tmp_people;

PHP is far from a functional programming language when compared to the likes of Clojure, Erlang, Haskell or even python, but functional tools like array_map can make everyday tasks easier.


Hi, I'm Steven Mercatante.
I build awesome things for the web using Python, JavaScript and Elixir.
Contact me if you'd like to work together.