简体   繁体   中英

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

Use shuffle() function.
shuffle($array);

http://php.net/manual/en/function.shuffle.php

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM