2

What I want is an efficient (without looping) way to merge arrays in the way that the first element of the resulting array is the first element of the first array, the second element of the resulting array is the second element of the second array (alternatively)... etc

Example:

$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);

$resultingArray = array(1, 2, 3, 4, 5, 6);
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
Hakim
  • 3,225
  • 5
  • 37
  • 75
  • 3
    What's inefficient about looping? Any solution that interleaves the arrays would have to at least go through them once, which is what a loop would do anyway. – Benjamin Gruenbaum Jul 14 '13 at 11:26
  • 1
    I believe the author of this question uses the word efficient, as not in terms of processing time, but in time of development. He does not want to write the code himself. It would be more efficient if there was a already a function that could do this. – Adam Jul 14 '13 at 11:29
  • Is it possible to use `array_merge` to achieve something similar. What I have really is an associative array (key => value), that I want to transform to an array containing alternatively key1, value1, key2, value2... – Hakim Jul 14 '13 at 11:41

2 Answers2

8

assuming both arrays have the same length.

$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);

$new = array();
for ($i=0; $i<count($arr1); $i++) {
   $new[] = $arr1[$i];
   $new[] = $arr2[$i];
}
var_dump($new);
DevZer0
  • 13,433
  • 7
  • 27
  • 51
1

Not that I'd really advocate this "hack", but this'll do:

$result = array();
array_map(function ($a, $b) use (&$result) { array_push($result, $a, $b); }, $arr1, $arr2);

It really just hides a double loop behind array_map, so, meh...

deceze
  • 510,633
  • 85
  • 743
  • 889
  • this solution is more pythonic (sorry php guys). but it will only work on `Php +5.3`. – Hakim Jul 14 '13 at 14:00
  • 1
    CAUTION: This will replace array keys with number indices. – Jhourlad Estrella May 21 '17 at 05:44
  • @JhourladEstrella Of course it is indexing the the output array. You are pushing elements from two arrays (which have identical original keys) into a new data structure where duplicated keys are not allowed. p.s. I don't generally like the idea of using `array_map()` when its return value is ignored. – mickmackusa Sep 09 '21 at 22:00
  • @JhourladEstrella for associative-safe versions of this technique, see [my answer on the dupe page](https://stackoverflow.com/a/69114863/2943403) – mickmackusa Sep 09 '21 at 22:33