note 83526 deleted from function.array-rand by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 11:00:48 +0000 |
| Subject: | note 83526 deleted from function.array-rand by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197013@lists.php.net to get a copy of this message | ||
Note Submitter: MadeGlobal
----
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;
}
?>