Home » Php » arrays – Inverse of php array_column function?

arrays – Inverse of php array_column function?

Posted by: admin February 25, 2020 Leave a comment


Given an array like

$x = array(array('a', 'aa'), array('b', 'bb'), array('c', 'cc'));

There is array_column that returns either

array_column($x, 0) === array('a', 'b', 'c')


array_column($x, 1) === array('aa', 'bb', 'cc') 

Now, is there an inverse? A function that would do:

array_putoneaftertheother(array('a', 'b', 'c'), array('aa', 'bb', 'cc')) === array(array('a', 'aa'), array('b', 'bb'), array('c', 'cc')) 

None come to my mind…

It’s pretty easy to implement, but I’m surprised that with so many array_* functions, PHP has no native version of this?!

How to&Answers:

You can do multiple arrays with array_map and no callback:

$result = array_map(null, array('a', 'b', 'c'), array('aa', 'bb', 'cc'));

Or with one larger array the same way with Argument unpacking via … (splat operator):

$result = array_map(null, ...array(array('a', 'b', 'c'), array('aa', 'bb', 'cc')));