PHP: How to select a random value from an array using a specified range
Posted on September 20, 2008, Filled under PHP,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
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.
- Leave a reply!
Sponsors
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 3 comments
-
PHP: How to remove empty values from an arrayat May 21, 2008 with 6 comments
