6

How to combine two arrays into single one and i am requesting this in such a way that the 3rd combination array should contains one value from one array and the next one from other array and so on.. or ( it could be random) ex:

$arr1 = (1, 2, 3, 4, 5);
$arr2 = (10, 20, 30, 40, 50);

and combined array

$arr3 = (1, 10, 2, 20, 3, 30, ...);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
KillerFish
  • 5,042
  • 16
  • 55
  • 64
  • Any difference with the count of array elements? – Shakti Singh Dec 07 '10 at 11:47
  • the output you show is not random but [a1,b1,a2,b2,…,an,bn]. In other words, the elements from the source arrays a and b are added in an alternating fashion to the resulting array in the order in which they appear in the source arrays – Gordon Dec 07 '10 at 11:54
  • Similar question: http://stackoverflow.com/questions/2815162/is-there-a-php-function-like-pythons-zip – orip Mar 12 '11 at 15:25

5 Answers5

18

If it can be random, this will solve your problem:

$merged = array_merge($arr1, $arr2);
shuffle($merged);
kapa
  • 77,694
  • 21
  • 158
  • 175
6

I also made a function for fun that will produce the exact output you had in your question. It will work regardless of the size of the two arrays.

function FosMerge($arr1, $arr2) {
    $res=array();
    $arr1=array_reverse($arr1);
    $arr2=array_reverse($arr2);
    foreach ($arr1 as $a1) {
        if (count($arr1)==0) {
            break;
        }
        array_push($res, array_pop($arr1));
        if (count($arr2)!=0) {
            array_push($res, array_pop($arr2));
        }
    }
    return array_merge($res, $arr2);
}
kapa
  • 77,694
  • 21
  • 158
  • 175
3

This will return a random array:

$merged = array_merge($arr1,$arr2);
shuffle($merged);
Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
1
sort($arr3 = array_merge($arr1, $arr2));

array_merge() will merge your arrays into one. sort() will sort the combined array.

If you want it random instead of sorted:

shuffle($arr3 = array_merge($arr1, $arr2));

$arr3 contains the array you're looking for.

Samuel Herzog
  • 3,561
  • 1
  • 22
  • 21
Yeroon
  • 3,223
  • 2
  • 22
  • 29
0

You can use

<?php
arr3 = array_merge ($arr1 , $arr2 );
print_r(arr3);
?>

which will output in

$arr3 = (1,2,3,4,5,10,20,30,40,50)
kapa
  • 77,694
  • 21
  • 158
  • 175
Wazy
  • 8,822
  • 10
  • 53
  • 98