I want to randomise part of an object array. Like I have an array of 10 elements and I want to sort first 5 entries in random order, where other/last 5 entries will be exactly same. Is there any easy/efficient way to do this is PHP? Thanks.
2 Answers
Use array_slice and shuffle.
$array = array_pad(array(), 10, ""); // 10 elements
$first = array_slice($array, 0, 5);
shuffle($first); // can't shuffle inline so do it like this
$array = array_merge($first, array_slice($array, 5, 5))
5 Comments
Jason McCreary
Your usage of
array_rand() is incorrect. You mean, shuffle() or pass the second parameter.Halcyon
I thought
array_rand did what shuffle does. PHP function naming is .. interesting. array_rand, even with the second parameter, doesn't return values, it always returns keys.u_mulder
By the way
array_rand also can be used. I think your previous version is workable tooHalcyon
No, because it returns keys. You can probably find a way to use it (
array_flip?), but this works and I'm happy with this.Jason McCreary
@u_mulder,
shuffle() is the appropriate function.You can split, then shuffle one, then combine them.
$myArr = ['a', 'b', 'c', 'd', 'e', 'f'];
$randArr = array_slice($myArr, 0, 3);
shuffle($randArr);
$staticArr = array_slice($myArr, 3);
$finalArr = array_merge($randArr, $staticArr);
shuffle