Frank Lucas
Frank Lucas

Reputation: 611

PHP reorder an array at random

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

Upvotes: 1

Views: 1938

Answers (2)

Aakash Martand
Aakash Martand

Reputation: 944

Use the shuffle() function.

shuffle($array);

Upvotes: 3

Md. Abutaleb
Md. Abutaleb

Reputation: 1635

$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.

Upvotes: 4

Related Questions