note 13909 modified in function.array-rand by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 14:48:51 +0000 |
| Subject: | note 13909 modified in function.array-rand by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-80015@lists.php.net to get a copy of this message | ||
If you're just trying to draw a random subset of n elements from an array, it seems more
effecient to do something like this:
<?php
function draw_rand_array($array,$draws)
{
$lastIndex = count($array) - 1;
$returnArr = array();
while($draws > 1)
{
$rndIndex = rand(0,$lastIndex);
array_push($returnArr,array_splice($array,$rndIndex,1));
$draws--;
$lastIndex--;
}
return $returnArr;
}
?>
No messing with indexes when you're done... you just have an array with the elements
you're looking for in it.
--was--
If you're just trying to draw a random subset of n elements from an array, it seems more
effecient to do something like this:
function draw_rand_array($array,$draws)
{
$lastIndex = count($array) - 1;
$returnArr = array();
while($draws > 1)
{
$rndIndex = rand(0,$lastIndex);
array_push($returnArr,array_splice($array,$rndIndex,1));
$draws--;
$lastIndex--;
}
return $returnArr;
}
No messing with indexes when you're done... you just have an array with the elements
you're looking for in it.
http://php.net/manual/en/function.array-rand.php