2

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)];
}
3
  • 1
    Use shuffle() Commented Jun 14, 2013 at 2:45
  • Why don't you use the second argument of array_rand instead of looping? Commented Jun 14, 2013 at 2:45
  • @felipe.zkn this is just an example. Commented Jun 14, 2013 at 2:46

4 Answers 4

3
$colors = array('blue', 'green', 'yellow', 'purple', 'white');
$colors = array_unique($colors);
shuffle($colors);
foreach($colors as $color)
  echo $color."\n";
Sign up to request clarification or add additional context in comments.

Comments

1

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');

1 Comment

this is not the thing i'm asking actually, while its in loop, the unique it must produce.
0

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);
}

Comments

0

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";
    }
?>

1 Comment

sorry but it always generates the same ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.