PHP:Get random value from array

From Juneday education
Jump to: navigation, search
#!/usr/bin/php

<?php

// Not so clever version:
$numbers = array(1,3,6,11,20,22,55,57,88,99);
print "The array is " . implode(" ", $numbers) . "\n";
$wantedNumber=random_int(1,99);
print "Looking for $wantedNumber\n";
$index = array_search($wantedNumber, $numbers);

while (! $index) { // PHP-screw-up : what about index 0? Thanks Edvin!
    print "$wantedNumber not found\n";
    $wantedNumber=random_int(1,99);
    print "Trying with $wantedNumber instead...";
    $index = array_search($wantedNumber, $numbers);
}
print "Found $wantedNumber at: $index\n";

?>

Expand using link to the right to see an alternative solution.

#!/usr/bin/php

<?php
$numbers = array(1,3,6,11,20,22,55,57,88,99);
print "The array is " . implode(" ", $numbers) . "\n";

print "\nAlternative version - get a random index instead:\n";
$wantedNumber = $numbers[random_int(0, count($numbers) - 1)];
print "A randomly selected number from the array is: $wantedNumber\n";
?>