Reputation: 22489
Hi I have a set or array:
$arr = ['1','2','3','4','5','6','7','8','9','0'];
shuffle($arr);
this will return the randomized order of the array. but how can I code if the '3','4'
and '8','9','0'
must together? I mean the other value can go random order but these '3','4'
and '8','9','0'
must join together.
Upvotes: 0
Views: 44
Reputation: 41885
Another way would be to get those ordered elements first (another copy), then shuffle the original, then remerge them again with union:
$arr = ['1','2','3','4','5','6','7','8','9','0'];
$arr2 = array_filter($arr, function($e){ // get those elements you want preversed
return in_array($e, [3, 4, 8, 9, 0]);
});
shuffle($arr); // shuffle the original
$ordered = $arr2 + $arr; // use union instead of array merge
ksort($ordered); // sort it by key
print_r($ordered);
Upvotes: 2
Reputation: 96159
Many possible solutions, one example
<?php
$arr = ['1','2',['3','4'],'5','6','7',['8','9','0']];
shuffle($arr);
// and then flatten the array ..somehow, e.g.
array_walk_recursive($arr, function($e) { echo $e, ' '; });
Upvotes: 1