Page 1 of 1

How to shuffle 2 arrays synchronously?

Posted: Thu Feb 23, 2006 8:17 am
by tomfra
I need to shuffle 2 arrays, which both have the same number of elements (but different values) "synchronously".

e.g.:

Original array 1:

[0] => value 1
[1] => value 2
[2] => value 3
[3] => value 4
[4] => value 5
[5] => value 6

Original array 2:

[0] => different value 1
[1] => different value 2
[2] => different value 3
[3] => different value 4
[4] => different value 5
[5] => different value 6


Shuffled Array 1:

[0] => value 2
[1] => value 4
[2] => value 1
[3] => value 5
[4] => value 6
[5] => value 3

Shuffled Array 2:

[0] => different value 2
[1] => different value 4
[2] => different value 1
[3] => different value 5
[4] => different value 6
[5] => different value 3


Any ideas?

Tomas

Posted: Thu Feb 23, 2006 8:28 am
by s.dot
You could merge them into one array with the keys as one array value, and the value as the other array value, then shuffle and split them back out

or just add them to a larger array

Code: Select all

$large_array = array();
foreach($array1 AS $k => $v){
   $large_array[] = array($v, $array2[$k]);
}

// large array would now be like this
//  Array (
//     [0] => Array (
//           [0] => Value 1 From First Array
//           [1] => Value 1 From Second Array
//        )
//       [1] => Array (
//           [0] => Value 2 From First Array
//           [1] => Value 2 From Second Array
//        )
//       [2] => Array (
//           [0] => Value 3 From First Array
//           [1] => Value 3 From Second Array
//       )
//   )

// shufle them
shuffle($large_array);

// pull them back out into their respective arrays
$array_one = array();
$array_two = array();

foreach($large_array AS $sub_array){
   foreach($sub_array AS $subarray){
      $array_one[] = $subarray[0];
      $array_two[] = $subarray[1];
   }
}
Untested and probably wrong :-D

Posted: Thu Feb 23, 2006 8:59 am
by onion2k
One idea..

Code: Select all

$array1 = array('a','b','c','d','e','f');
$array2 = array('A','B','C','D','E','F');

$array3 = range(0,count($array1));
shuffle($array3);

foreach ($array3 as $x) {
  echo $array1[$x] . "=" . $array2[$x];
}

Posted: Thu Feb 23, 2006 12:41 pm
by tomfra
Thanks for the ideas! I will try it but I am sure it will work.

Tomas