0

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.

0

2 Answers 2

2

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);

Sample Output

Sign up to request clarification or add additional context in comments.

1 Comment

ngayun ko lng na notice, Hokage Du30 ikaw ba yan?
1

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, ' '; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.