Recipe 23.9. Randomizing All Lines in a File


23.9.1. 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.

23.9.2. Solution

Read all the lines in the file into an array with file( ) , and then shuffle the elements of the array, as in Example 23-27.

Randomizing all lines in a file

<?php $lines = file('quotes-of-the-day.txt'); $lines = shuffle($lines); ?>

23.9.3. Discussion

The shuffle( ) function randomly reorders the array elements, so after shuffling, you can pick out $lines[0] as a quote to display.

23.9.4. See Also

Recipe 4.20 for shuffle( ); 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