18.11. Randomizing All Lines in a File
Problem
You want to randomly reorder all lines in a file. You have a file of funny quotes, for example, and you want to pick out one at random.
Solution
Read all the lines in the file into an array with file( )
, and then shuffle the
elements of the array:
$lines = file('quotes-of-the-day.txt'); $lines = pc_array_shuffle($lines);
Discussion
The pc_array_shuffle( )
function from Section 4.21 is more random than PHP’s
built-in shuffle( )
function, because it uses the
Fisher-Yates shuffle, which equally
distributes the elements throughout the array.
See Also
Section 4.20 for pc_array_shuffle( )
; documentation on shuffle( )
at
http://www.php.net/shuffle.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.