note 83526 modified in function.array-rand by felipe
| From: | felipe@php.net | Date: | Fri, 30 May 2008 11:29:38 +0000 |
| Subject: | note 83526 modified in function.array-rand by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-139996@lists.php.net to get a copy of this message | ||
A problem exists with the array_pick function suggested by adrian.quark - if the function only has
to remove one item from the array (e.g. original array has five entries and you want it to return
four), you get a problem with the different behavior of array_rand when the parameter is 1
Fixed implementation:
<?php
function array_pick($hash, $num) {
$count = count($hash);
if ($num <= 0) return array();
if ($num >= $count) return $hash;
$required = $count - $num;
if ($required == 1) { //array rand returns the KEY if there is only one item requested so...
$keys = array(array_rand($hash, $required));
} else
$keys = array_rand($hash, $required);
foreach ($keys as $k) unset($hash[$k]);
return $hash;
}
?>
--was--
A problem exists with the array_pick function suggested by adrian.quark - if the function only has
to remove one item from the array (e.g. original array has five entries and you want it to return
four), you get a problem with the different behavior of array_rand when the parameter is 1
Fixed implementation :
function array_pick($hash, $num) {
$count = count($hash);
if ($num <= 0) return array();
if ($num >= $count) return $hash;
$required = $count - $num;
if ($required == 1) { //array rand returns the KEY if there is only one item requested so...
$keys = array(array_rand($hash, $required));
} else
$keys = array_rand($hash, $required);
foreach ($keys as $k) unset($hash[$k]);
return $hash;
}
http://php.net/manual/en/function.array-rand.php