note 107813 added to function.array-rand

From: Date: Wed, 07 Mar 2012 13:18:36 +0000
Subject: note 107813 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-186521@lists.php.net to get a copy of this message
An example for getting random value from arrays; <?php function array_random($arr, $num = 1) { shuffle($arr); $r = array(); for ($i = 0; $i < $num; $i++) { $r[] = $arr[$i]; } return $num == 1 ? $r[0] : $r; } $a = array("apple", "banana", "cherry"); print_r(array_random($a)); print_r(array_random($a, 2)); ?> cherry Array ( [0] => banana [1] => apple ) And example for getting random value from assoc arrays; <?php function array_random_assoc($arr, $num = 1) { $keys = array_keys($arr); shuffle($keys); $r = array(); for ($i = 0; $i < $num; $i++) { $r[$keys[$i]] = $arr[$keys[$i]]; } return $r; } $a = array("a" => "apple", "b" => "banana", "c" => "cherry"); print_r(array_random_assoc($a)); print_r(array_random_assoc($a, 2)); ?> Array ( [c] => cherry ) Array ( [a] => apple [b] => banana ) ---- Server IP: 69.147.83.197 Probable Submitter: 194.27.149.90 ---- Manual Page -- http://www.php.net/manual/en/function.array-rand.php Edit -- https://master.php.net/note/edit/107813 Del: integrated -- https://master.php.net/note/delete/107813/integrated Del: useless -- https://master.php.net/note/delete/107813/useless Del: bad code -- https://master.php.net/note/delete/107813/bad+code Del: spam -- https://master.php.net/note/delete/107813/spam Del: non-english -- https://master.php.net/note/delete/107813/non-english Del: in docs -- https://master.php.net/note/delete/107813/in+docs Del: other reasons-- https://master.php.net/note/delete/107813 Reject -- https://master.php.net/note/reject/107813 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186521) next »