Inverse of PHP’s array_combine

Posted on by Chris Warburton

Another shameless re-post of an answer I gave on Stack Overflow. This time it’s about a function to split an array into its keys and its values, ie. an inverse of array_combine.

Unfortunately there is no built-in inverse of array_combine. There is also no way to define one, since array_combine expects multiple parameters and we can’t return multiple values from a function.

We can construct an alternative to array_combine which takes a single argument: the array of keys and the array of values wrapped up together in another array. This transformation is called “uncurrying” and is performed by call_user_func_array:

$array_comb  = function($arr) { return call_user_func_array('array_combine', $arr); };

This alternative function does have an inverse:

$array_split = function($arr) { return array(array_keys($arr), array_values($arr)); };

If we define function composition:

$compose  = function($f, $g) {
    return function($x) use ($f, $g) { return $f($g($x)); };
};

Then the following functions are all (extensionally) equal, ie. they all return their argument unchanged:

$identity      = function($x) { return $x; };
$left_inverse  = $compose($array_split, $array_comb);  // Split then combine
$right_inverse = $compose($array_comb, $array_split);  // Combine then split

Note that they accept different argument types though: