0

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.

3
  • Show us your tried code of awesomeness Commented Jun 25, 2013 at 17:54
  • Sorry, not array_shuffle, shuffle Commented Jun 25, 2013 at 17:54
  • There is not a single function. However, you can combine a few of the PHP array functions. What you have tried? Commented Jun 25, 2013 at 17:57

2 Answers 2

5

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))
Sign up to request clarification or add additional context in comments.

5 Comments

Your usage of array_rand() is incorrect. You mean, shuffle() or pass the second parameter.
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.
By the way array_rand also can be used. I think your previous version is workable too
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.
@u_mulder, shuffle() is the appropriate function.
1

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

1 Comment

Note that shuffle does not return the array - like sort() it takes the variable by reference, then returns true on success or false on failure.

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.