note 11719 modified in function.array-rand by irc-html

From: Date: Sat, 19 Jan 2002 21:08:46 +0000
Subject: note 11719 modified in function.array-rand by irc-html
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-25473@lists.php.net to get a copy of this message
It is true that array_rand() returns with the selected records in the same order as the original array. If you want otherwise, consider shuffle() on the result. Note that there is concern over the correctness of the shuffle() implementation. There exists an O(n) algorithm to shuffle an array thorougly and reliably: $c = count($foo); for ($i=0; $i<$c; $i++) { $d = mt_rand(0, $i); $tmp = $foo[$i]; $foo[$i] = $foo[$d]; $foo[$d] = $tmp; } This, of course, assumes that your keys are sequential and start at zero. If that's not the case, you can use array_keys() to get a sequential map of keys, I think. The rest is left as an excersise. --was-- It is true that array_rand() returns with the selected records in the same order as the original array. If you want otherwise, consider shuffle() on the result. Note that there is concern over the correctness of the shuffle() implementation. There exists an O(n) algorithm to shuffle an array thorougly and reliably: $c = count($foo); for ($i=0; $i<$c; $i++) { $d = mt_rand(); $tmp = $foo[$i]; $foo[$i] = $foo[$d]; $foo[$d] = $tmp; } This, of course, assumes that your keys are sequential and start at zero. If that's not the case, you can use array_keys() to get a sequential map of keys, I think. The rest is left as an excersise. http://www.php.net/manual/en/function.array-rand.php

« previous php.notes (#25473) next »