简体   繁体   中英

Select Random Unique String From List in PHP

i want to echo colors which will be selected from list, but they must be unique. I know how to generate unique things in general but don't have any idea on how to do that if there is a proper list.

also it must do this in a loop, that's why i did it with for loop below.

for example, in the starting, assume that array has 5 elements, and within the first loop it will select blue and echo that, after echoing the blue, in the second loop, there will be 4 options, it will echo one of the remaining four elements randomly, blue wont be in the options.

for instance, in my purpose it must generate like : blue - white - green - yellow - purple ( unique )

the false one is : blue - blue - green - yellow - purple ( not unique )

$colors= array('blue', 'green', 'yellow', 'purple', 'white');
for($i = 1; $i <=5; $i++){
echo $colors[array_rand($colors)];
}
$colors = array('blue', 'green', 'yellow', 'purple', 'white');
$colors = array_unique($colors);
shuffle($colors);
foreach($colors as $color)
  echo $color."\n";

You can use array_unique in PHP.

for example if you generate an array as follows.

$array = array('blue','blue','green','yellow','purple');
$out = array_unique($array);

//will product
//array('blue', 'green', 'yellow', 'purple');

Note from PHP.net: 5.2.10 The resulting array of keys is no longer shuffled. So array_rand() like I said is no more possible to use. Instead you can use:

<?php
    $colors = array('blue', 'green', 'yellow', 'purple', 'white');    
    shuffle($colors);

    foreach ($colors as $shuffledColor) {
        echo $shuffledColor . "\n";
    }
?>

You could try copying the array, then shuffling the copy and finally popping the results.

For example:

$array = array('blue','green','yellow','purple');
$copy = $array;
shuffle($copy);
while(!empty($copy)){
    echo array_pop($copy);
}

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