Shuffle multiple arrays in the same way

Say you have multiple arrays of the same length which you want to shuffle. But they are “row” arrays, in which the “columns” need to stay the same as order is changed.

For example, if I had three arrays like so:

$colors = array('red', 'blue', 'green', 'yellow');
$numbers = array(1, 2, 3, 4);
$shapes = array('circle', 'square', 'triangle', 'pentagon'); 

And then after the shuffle of which I speak you might have:

$colors = array( 'green', 'yellow', 'red', 'blue');
$numbers = array(3, 4, 1, 2);
$shapes = array('triangle', 'pentagon', 'green', 'square', ); 

In other words, the position of “green” always matches “3” always matches “triangle.”

This does the trick:

if (my arrays all equal each other, exercise for user) ) {
			$count = count($colors);
			$order = range(1, $count);

			shuffle($order);
			array_multisort($order, $colors, $numbers, $shapes);
		}

4 thoughts on “Shuffle multiple arrays in the same way

  1. function takes any number of arrays as arguments and returns an array of those values that exist in each. If multiple keys have the same value, the first key with that value is preserved.

  2. To do exactly what you ask (the law, not the spirit of the law), you will have to add additional arrays and pull items over. In addition, for each array, you will need a List or similar to store the items you have already randomly pulled over. After that, things are simple. Use the Random class to create random numbers, check if the item has already been moved (using the List), if not store the result in the new array/list, add the value to your List to make sure you do not move the same item twice. Once everything is moved, set this new array to the old array.

  3. Well, they can’t BOTH be accessing the same array and if you use a lock, or a mutex or any other synchronizing mechanism, you kinda lose the power of the threads (since one will have to wait for another, either to finish the shuffling or finish a bit of the shuffling). Why don’t you just divide the array in half, give each thread its bit of the array and then merge the two arrays?

What say you?