0

I currently have a piece of code that is selecting random values from an array but I would like to prevent it from selecting duplicate values. How can I achieve this? This is my code so far:

$facilities = array("Blu-ray DVD Player","Chalk board","Computer", "Projector",
"Dual data projector", "DVD/Video");

for($j = 0; $j < rand(1, 3); $j++)
   {
    $fac =  print $facilities[array_rand($facilities, 1)] . '<br>'; 
   } 

2 Answers 2

5

I think you should look at array_rand

$facilities = array("Blu-ray DVD Player","Chalk board","Computer","Data projector","Dual data projector","DVD/Video");
$rand = array_rand($facilities, 2);
                                ^----- Number of values you want 

foreach ( $rand as $key ) {
    print($facilities[$key] . "<br />");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why won't it work with array_rand($facilities, 1);. I've tried $rand = array_rand($facilities, rand(1, 3)); but it doesn't work
echo $facilities[array_rand($facilities)] ; that is how to get only one element
2

You can return multiple random keys from array_rand() by specifying the number to return as the second parameter.

$keys = (array) array_rand($facilities, rand(1, 3));
shuffle($keys); // array_rand() returns keys unshuffled as of 5.2.10

foreach ($keys as $key) {
    echo $facilities[$key] . '<br>';
}

1 Comment

The only thing worth pointing out is that this will fail ungracefully if rand(1, 3) is 1.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.