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!

Get our RSS Feed!

Sponsors

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled