0

I have the following two arrays. I need a way in PHP to combine them together so that the values at index[i] from both arrays are added to the same index in the final array.

Array 1

[0] => '123456'
[1] => '654123'
[2] => '987456'
[3] => '489522'
[4] => '014779'

Array 2

[0] => 'feature'
[1] => 'promo'
[2] => 'other'
[3] => 'start'
[4] => 'end'

Final Array I need

[0] => ['123456', 'feature']
[1] => ['654123', 'promo']
[2] => ['987456', 'other']
[3] => ['489522', 'start']
[4] => ['014779', 'end']

4 Answers 4

10

By far the easiest way is to use array_map:

$result = array_map(null, $array1, $array2));

See it in action.

Sign up to request clarification or add additional context in comments.

1 Comment

And the most elegant... :)
1
foreach ($array1 as $index => $value1) {
    $finalArray[$index] = array($value1, $array2[$index]);
}

2 Comments

First answer? Mine was earlier and more detailed!
@PDev: Your answer has three code snippets, only the second of which works as intended. The other two just detract from its value.
0

As both have a numeric key, you can do it with foreach:

foreach ($array2 as $key => $value) {
    $finalArray[$value] = $array1[$key];
}

It's a simple solution, but it should work. It just gets each value of the second array and puts it into the final array.

Or, if you need a number in the final array also:

foreach ($array2 as $key => $value) {
    $finalArray[$key] = array($value, $array1[$key]);
}

Or, the easiest way is to just use the array_merge function:

$finalArray = array_merge($array1, $array2);

Manual here.

Hope it helps you.

Comments

0

Try this snippet :)

 $array_combined = array();
 foreach($array1 as $key=>$value)
 {
    $array_combined[$key] = array($array1[$key], $array2[$key]); 
 }

Comments

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.