note 83526 added to function.array-rand

From: Date: Fri, 30 May 2008 10:16:07 +0000
Subject: note 83526 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-139993@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 : 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; } ---- Server IP: 80.64.47.13 Probable Submitter: 87.111.44.142 ---- Manual Page -- http://www.php.net/manual/en/function.array-rand.php Edit -- https://master.php.net/note/edit/83526 Del: integrated -- https://master.php.net/note/delete/83526/integrated Del: useless -- https://master.php.net/note/delete/83526/useless Del: bad code -- https://master.php.net/note/delete/83526/bad+code Del: spam -- https://master.php.net/note/delete/83526/spam Del: non-english -- https://master.php.net/note/delete/83526/non-english Del: in docs -- https://master.php.net/note/delete/83526/in+docs Del: other reasons-- https://master.php.net/note/delete/83526 Reject -- https://master.php.net/note/reject/83526 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#139993) next »