PHP: How to select a random value from an array using a specified range
Posted on September 20, 2008, under PHP,
Bookmark it
Hi,
Here’s a script which randomly selects a value from an array:
<?php
function selectRandomValueFromArray($array, $range = '')
{
srand((float) microtime() * 10000000);
if(empty($range))
{
$last_key = count($array) - 1;
$range = array(0, $last_key);
}
$rand_array = rand($range[0], $range[1]);
$result = $array[$rand_array];
return $result;
}
$array = array('apple', 'pine', 'pear', 'strawberry', 'cherries', 'mango', 'grape', 'watermelon', 'papaya');
/*
1st argument: array
2nd argument (optional): the array range (2 values) of the keys
*/
echo selectRandomValueFromArray($array); // select random value from all
echo "<br />";
echo selectRandomValueFromArray($array, array(0, 3)); // select random value from the first 4 values of the array
echo "<br />";
echo selectRandomValueFromArray($array, array(2, 5)); // select random value between the 3rd and the 6th value of the array
?>
NOTE The array starts from 0. If you need, for instance, to set a range from the 2nd to the 5th value of the array then you should use the following argument: array(1, 4).
The advantage of this function, compared to array_rand() is that it can randomly select values from a specified range.
Good luck!
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 20, 2008
- article by Gabriel C.
- Share your thoughts!
Related Posts
-
Display Values from an Array in Random Orderat October 2, 2008
-
How to generate a random password in PHPat August 29, 2008 with 2 comments
-
PHP: Usage of Range() Function (Alphabetical & Numerical Output)at September 2, 2008
-
Show random image(s) from a directoryat September 21, 2008 with 6 comments
-
PHP: How to remove empty values from an arrayat May 21, 2008 with 10 comments
