note 23565 modified in function.array-rand by vrana

From: Date: Tue, 17 Aug 2004 14:48:48 +0000
Subject: note 23565 modified in function.array-rand by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-79984@lists.php.net to get a copy of this message
If you just want to pull one random element from an array, try something like this: <?php mt_srand((double) microtime() * 1000000); $myarray = array("this", "is", "a", "test", "to", "see", "if", "I", "can", "pull", "one", "element", "from", "an", "array", "randomly"); $random_index = mt_rand(0, (count($myarray)-1)); ?> Then to test the randomness or what have you try a simple: <?php $string = ""; // Just to kill the warning for ($i=0; $i<count($myarray); $i++) { $random_index = mt_rand(0, (count($myarray)-1)); $string .= "$myarray[$random_index] "; } $string = rtrim($string); echo ($string); ?> I've gotten extremely good output from this method and would recommend it if you're just pulling one element. --was-- If you just want to pull one random element from an array, try something like this: mt_srand((double) microtime() * 1000000); $myarray = array("this", "is", "a", "test", "to", "see", "if", "I", "can", "pull", "one", "element", "from", "an", "array", "randomly"); $random_index = mt_rand(0, (count($myarray)-1)); Then to test the randomness or what have you try a simple: $string = ""; // Just to kill the warning for ($i=0; $i<count($myarray); $i++) { $random_index = mt_rand(0, (count($myarray)-1)); $string .= "$myarray[$random_index] "; } $string = rtrim($string); echo ($string); I've gotten extremely good output from this method and would recommend it if you're just pulling one element. http://php.net/manual/en/function.array-rand.php

« previous php.notes (#79984) next »