note 27317 modified in function.array-rand by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 14:48:44 +0000 |
| Subject: | note 27317 modified in function.array-rand by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-80017@lists.php.net to get a copy of this message | ||
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:
<?php
$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<BR>";
?>
// 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.
<?php
$random_array = array();
foreach($rand_keys as $value)
{
array_push($random_array, $some_array[$value]);
}
print_r($random_array);
?>
--was--
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<BR>";
// 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);
http://php.net/manual/en/function.array-rand.php