note 27320 deleted from function.array-rand by sniper
| From: | sniper@php.net | Date: | Fri, 06 Jun 2003 19:49:30 +0000 |
| Subject: | note 27320 deleted from function.array-rand by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-49910@lists.php.net to get a copy of this message | ||
Note Submitter: mickoz[at]parodius[dot]com
----
For those of you thinking that it does not work for num_req = 1, it is because it return a variable
and not an array. This mainly cause some problem with people using foreach.
The correct way to handle this is explained by that example:
$some_array = array("blah","bleh","foo","lele");
$nb_value = 1;
srand ((float) microtime() * 10000000);
$rand_keys = array_rand($some_array, $nb_value);
if(!is_array($rand_keys))
{
$rand_keys = array($rand_keys);
}
print_r($rand_keys); // verify here the array of keys
echo "\n";
// You can then correctly use the foreach, as it require an array to work
// If you use foreach with one element, it won't work.
$random_array = array();
foreach($rand_keys as $value)
{
array_push($random_array, $some_array[$value]);
}
print_r($random_array);