PHP Files Randomizing All Lines in a File - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Files Randomizing All Lines in a File - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, July 10, 2019

PHP Files Randomizing All Lines in a File

PHP Files 


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(__DIR__ . '/quotes-of-the-day.txt');

       if (shuffle($lines)) {
              // okay
       } else {
              die("Failed to shuffle");
       }

Discussion

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

No comments:

Post a Comment

Post Top Ad