note 27317 added to function.array-rand

From: Date: Mon, 02 Dec 2002 02:28:23 +0000
Subject: note 27317 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-40231@lists.php.net to get a copy of this message
For those of you thinking that it does not work for num_req = 1, it is because it return a variable and not an array. This mainly cause some problem with people using foreach. The correct way to handle this is explained by that example: $some_array = array("blah","bleh","foo","lele"); $nb_value = 1; srand ((float) microtime() * 10000000); $rand_keys = array_rand($some_array, $nb_value); if(!is_array($rand_keys)) { $rand_keys = array($rand_keys); } print_r($rand_keys); // verify here the array of keys echo "\n<BR>"; // You can then correctly use the foreach, as it require an array to work // If you use foreach with one element, it won't work. $random_array = array(); foreach($rand_keys as $value) { array_push($random_array, $some_array[$value]); } print_r($random_array); -- http://www.php.net/manual/en/function.array-rand.php http://master.php.net/manage/user-notes.php?action=edit+27317 http://master.php.net/manage/user-notes.php?action=delete+27317 http://master.php.net/manage/user-notes.php?action=reject+27317

« previous php.notes (#40231) next »