note 67848 added to function.array-rand

From: Date: Wed, 05 Jul 2006 21:12:13 +0000
Subject: note 67848 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-114425@lists.php.net to get a copy of this message
Following are functions for getting a random key or value (or array of random keys or values) from a filtered array. In other words, given an array of data, these functions filter out what you don't want, then extract a random element or bunch from what's left. $CallBack is the filtering function. // Utility function for functions below function GetRandomArrayValue($TheArray) { return $TheArray[array_rand($TheArray)]; } // Get a random key or array of keys from a filtered array function GetRandomFilteredArrayKeys($aInput, $CallBack = NULL, $NumReq = 1) { $FilteredKeys = array_keys(array_filter($aInput, $CallBack)); if ($NumReq <= 1) { return GetRandomArrayValue($FilteredKeys); } else { shuffle($FilteredKeys); return array_slice($FilteredKeys, 0, $NumReq); } } // Get a random value or array of values from a filtered array function GetRandomFilteredArrayValues($aInput, $CallBack = NULL, $NumReq = 1) { $aFiltered = array_filter($aInput, $CallBack); if ($NumReq <= 1) { return $aFiltered[GetRandomArrayValue(array_keys($aFiltered))]; } else { shuffle($aFiltered); return array_slice($aFiltered, 0, $NumReq); } } ---- Server IP: 216.194.113.175 Probable Submitter: 66.217.117.92 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.array-rand.php Edit -- http://master.php.net/note/edit/67848 Del: integrated -- http://master.php.net/note/delete/67848/integrated Del: useless -- http://master.php.net/note/delete/67848/useless Del: bad code -- http://master.php.net/note/delete/67848/bad+code Del: spam -- http://master.php.net/note/delete/67848/spam Del: non-english -- http://master.php.net/note/delete/67848/non-english Del: in docs -- http://master.php.net/note/delete/67848/in+docs Del: other reasons-- http://master.php.net/note/delete/67848 Reject -- http://master.php.net/note/reject/67848 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#114425) next »