0

I have three arrays:

['a', 'apple', 'albania'];
['b', 'banana', 'brasil'];
['c', 'carrot', 'croatioa'];

I want to convert those three arrays to:

['a', 'b', 'c'];
['apple', 'banana', 'carrot'];
['albania', 'brasil', 'croatioa'];

How can I do it? I want the values with key 0 to form a new array and so on with all the keys

Any suggestion will be received.

Thank you!

6
  • 2
    Stack Overflow is not a free code writing service. You are expected to try to write the code yourself. After doing more research if you have a problem you can post what you've tried with a clear explanation of what isn't working and providing a Minimal, Complete, and Verifiable example. I suggest reading How to Ask a good question. Commented May 4, 2017 at 5:08
  • Of course, I know that. I just need a direction. Commented May 4, 2017 at 5:09
  • 2
    1) You could create a big array, loop over the inner arrays and create new array for each key (0, 1, 2). 2) Create 3 arrays loop over the old arrays and move each key (0, 1, 2) with it value to the corresponding new array. Commented May 4, 2017 at 5:11
  • I was trying to avoid using loops. isn't there a function that do this? Commented May 4, 2017 at 5:12
  • 1
    @DavSev - this isn't a common requirement, and so I cannot think of an inbuilt PHP function that will do this. I'd start with Tom Udding's suggestion and see how you go. Come back if you need more help. Commented May 4, 2017 at 5:17

1 Answer 1

4

you can use array_map() that will return one array that consists of three arrays

$arr1 = ['a', 'apple', 'albania'];
$arr2 = ['b', 'banana', 'brasil'];
$arr3 = ['c', 'carrot', 'croatioa'];

$newArr = array_map(function($a, $b, $c){
    return [$a,$b,$c];
},$arr1, $arr2, $arr3);

print_r($newArr);
Sign up to request clarification or add additional context in comments.

4 Comments

if you loop the $newArr, you will get the requested output.
Perhaps out of scope of the original request, but might this cause erroneous output if the source arrays are not equal in length? Just something to be mindful of. But excellent solution.
it is still okay if you have different array length
I thought you'd get null values when a value didn't exist in a shorter array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.