Reputation: 13216
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>';
}
Upvotes: 0
Views: 86
Reputation: 51950
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>';
}
Upvotes: 2
Reputation: 95131
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 />");
}
Upvotes: 5