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, ...);
Agustin Meriles
  • 4,762
  • 3
  • 29
  • 44
KillerFish
  • 4,914
  • 15
  • 54
  • 63
  • 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
  • 75,446
  • 20
  • 155
  • 173
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
  • 75,446
  • 20
  • 155
  • 173
3

This will return a random array:

$merged = array_merge($arr1,$arr2);
shuffle($merged);
Jonathon Bolster
  • 15,681
  • 3
  • 41
  • 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
  • 21
  • 21
Yeroon
  • 3,185
  • 2
  • 21
  • 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
  • 75,446
  • 20
  • 155
  • 173
Wazy
  • 8,695
  • 10
  • 53
  • 97