Reputation:
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)];
}
Upvotes: 2
Views: 651
Reputation: 2060
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";
}
?>
Upvotes: 0
Reputation: 101
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);
}
Upvotes: 0
Reputation: 11690
$colors = array('blue', 'green', 'yellow', 'purple', 'white');
$colors = array_unique($colors);
shuffle($colors);
foreach($colors as $color)
echo $color."\n";
Upvotes: 3
Reputation: 13535
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');
Upvotes: 1