2

I need to reorder an array at random but I am not sure what the best/cleanest/fastest way is to do this.

So what I am trying to achieve is the following. Let's say I have an array that looks like this:

$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);

My goal is to get something like this but at random:

$array = array(6, 4, 4, 10, 4, 6, 4, 6, 60, 6, 8, 6, 10, 40, 8, 20);

Here's what I've been trying but it doesn't seem to be working as intended:

$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);
$newArray = array();

$randomNumber = rand(0 , 14);

for ($x = 0; $x <= 15; $x++) {
    $newArray[$x] = $array[$randomNumber];
}

Many thanks in advance to anyone who can help me out :)

4
  • 5
    shuffle( $array ). Commented Nov 22, 2016 at 7:19
  • @Darren Is it that simple? I am trying to build something in PHP that I have built in C# and it was a lot harder in C# lol :) Commented Nov 22, 2016 at 7:28
  • Haha it is indeed, you simply run that function and it'll shuffle the current array :) Commented Nov 22, 2016 at 7:28
  • @Darren okay cool thanks a lot! :) Commented Nov 22, 2016 at 7:30

2 Answers 2

5
$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);

Check the output of previous array

echo "<pre>";
print_r($array);
echo "</pre>";

Shuffling previous array & check output again.

shuffle($array);
print_r($array);

Now run a foreach loop like

foreach($array as $item){
  echo $item;
}

Note: You don't need to store shuffle data to new array.

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

Comments

3

Use the shuffle() function.

shuffle($array);

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.