Page 1 of 1

write a foreach statement to print quotes from a text file!

Posted: Tue Jun 22, 2010 9:20 pm
by canadian_angel
I need to write a foreach statement that will print quotes from a text file, I tried to below but keep getting only one quote at a time and it needs to print 5.
Just wondering if anyone can help me figure this out, I did attempt it myself, but no luck. The text file is called quotes.txt


Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
        <title>View a Quotation</title>
    </head>
    <body>
        <?php // Script 11.3 - view_quote.php
        // This script displays and handles an HTML form.
        // This script takes text input and stores it in a text file.
        
        // Address error handling.
        ini_set ('display_errors', 1);
        error_reporting (E_ALL & ~E_NOTICE);
        
        // Read the file's contents into an array.
        $data = file ('../chapter11/quotes.txt');
        
        // Count the number of items in the array.
        $n = count ($data);
        
        // Pick a random item.
        $rand = rand (0, ($n - 1));
        
        // Pick the quotation.
        print '<p>' . trim ($data[$rand]) . '</p>';

         // Print each quotation from quotes.txt.
        foreach ($quotes as $key => $quotes) {
            print "<p>$quotes</p>\n;";
        }
        
        ?>
    </body>
</html>

Re: write a foreach statement to print quotes from a text fi

Posted: Tue Jun 22, 2010 10:30 pm
by Phoenixheart
Why don't you use array_rand?

Re: write a foreach statement to print quotes from a text fi

Posted: Wed Jun 23, 2010 12:43 am
by requinix
If you need more than one and they must be unique (no duplicates) then shuffle the array and choose the first however-many-you-want from it.