Can I choose some elements in an array and shuffle it in PHP? You know, when you use
shuffle(array)
, It shuffles all elements in an array, but I just want to shuffle some elements in an array while keep other elements unchanged, how to do it?
Can I choose some elements in an array and shuffle it in PHP? You know, when you use
shuffle(array)
, It shuffles all elements in an array, but I just want to shuffle some elements in an array while keep other elements unchanged, how to do it?
You can use array_slice
to copy the part of the array you want to shuffle, shuffle the copy, and then use array_splice
to copy the shuffled data back into the original array.
EDIT: More generally, if you know the keys of the items you want to shuffle, put them in an array called $keys
. Then:
// Get out the items to shuffle.
$work = array();
foreach ($keys as $i => $key) {
$work[$i] = $myarray[$key];
}
shuffle($work); // shuffle them
// And put them back.
foreach ($keys as $i => $key) {
$myarray[$key] = $work[$i];
}
(Sorry if this has some mistakes; my PHP is rusty and I'm not near a computer where I can test it!)
Something very similar will work for a multidimensional array. Each element of $keys
could be an array of indices, and instead of $myarray[$key]
you would write $myarray[$key[0]][$key[1]]
.
Consider the following
function swap(&$a, &$b) { list($a, $b) = array($b, $a); }
$len = count($a);
for($i = 0; $i < $len; $i++) {
$j = rand(1, $len) - 1;
swap($a[$i], $a[$j]);
}
this is the standard loop that shuffles all array elements. To shuffle only some ("movable") elements, let's put their keys into an array
$keys = array(1, 3, 5, 7, 9, 11, 13, 17);
and replace the loop over $a with the loop over $keys
$len = count($keys);
for($i = 0; $i < $len; $i++) {
$j = rand(1, $len) - 1;
swap($a[$keys[$i]], $a[$keys[$j]]);
}
this moves elements in positions 1, 3, 5 etc. and leaves other elements in place