note 56291 added to function.array-rand
| From: | bjcffnet at gmail dot com | Date: | Mon, 29 Aug 2005 23:29:58 +0000 |
| Subject: | note 56291 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-94357@lists.php.net to get a copy of this message | ||
As wazaawazaa600 at msn dot com pointed out, a multi-dimensional array doesn't work with this
function. So, I hope I can help someone with this :)
<?php
/**
* Returns a number of random elements from an array.
*
* It returns the number (specified in $limit) of elements from
* $array. The elements are returned in a random order, exactly
* as it was passed to the function. (So, it's safe for multi-
* dimensional arrays, aswell as array's where you need to keep
* the keys)
*
* @author Brendan Caffrey <bjcffnet at gmail dot com>
* @param array $array The array to return the elements from
* @param int $limit The number of elements to return from
* the array
* @return array The randomized array
*/
function array_rand_keys($array, $limit = 1) {
$count = @count($array)-1;
// Sanity checks
if ($limit == 0 || !is_array($array) || $limit > $count) return array();
if ($count == 1) return $array;
// Loop through and get the random numbers
for ($x = 0; $x < $limit; $x++) {
$rand = rand(0, $count);
// Can't have double randoms, right?
while (isset($rands[$rand])) $rand = rand(0, $count);
$rands[$rand] = $rand;
}
$return = array();
$curr = current($rands);
// I think it's better to return the elements in a random
// order, which is why I'm not just using a foreach loop to
// loop through the random numbers
while (count($return) != $limit) {
$cur = 0;
foreach ($array as $key => $val) {
if ($cur == $curr) {
$return[$key] = $val;
// Next...
$curr = next($rands);
continue 2;
} else {
$cur++;
}
}
}
return $return;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+56291
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56291&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56291&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56291&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56291&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56291&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56291&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+56291&report=yes
Search -- http://master.php.net/manage/user-notes.php