2

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')

or 

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?!

2
  • A side note: I wouldn't really call it inverse of array_column(). array_column() returns a "vertical slice". Inverse/opposite of this would be a horizontal slice (or maybe everything except that column, but let's not go there), which is just $x[n]. What you described seems like rotating a 2D array, so rows become columns and columns become rows. Commented Feb 18, 2020 at 13:47
  • @akinuri I called this "inverse" because then array_column(array_putoneaftertheother($x, $y), 0) === $x so like f • g = Id meaning f function is g inverse. Opposite would be f•g=0 Tho you may indeed consider this as a transpose function of the array('a','b','c') vector Commented Feb 18, 2020 at 13:55

1 Answer 1

7

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')));
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, indeed! I didn't got the "NULL [...] perform a zip operation on multiple arrays" of the doc, but I should have digged more into the examples, as this is the example #4 and #5 of doc php.net/manual/en/function.array-map.php Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.