Recipe 4.20. Randomizing an Array


4.20.1. Problem

You want to scramble the elements of an array in a random order.

4.20.2. Solution

Use shuffle( ):

shuffle($array);

4.20.3. Discussion

It's suprisingly tricky to properly shuffle an array. In fact, up until PHP 4.3, PHP's shuffle( ) routine wasn't a truly random shuffle. It would mix elements around, but certain combinations were more likely than others.

Therefore, you should use PHP's shuffle( ) function whenever possible.

4.20.4. See Also

Documentation on shuffle( ) at http://www.php.net/shuffle.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net