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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
canadian_angel
Forum Commoner
Posts: 31
Joined: Fri Jun 11, 2010 3:13 pm

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

Post 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>
Last edited by Benjamin on Tue Jun 22, 2010 9:22 pm, edited 1 time in total.
Reason: Added [syntax=php] tags.
Phoenixheart
Forum Contributor
Posts: 123
Joined: Tue Nov 16, 2004 7:46 am
Contact:

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

Post by Phoenixheart »

Why don't you use array_rand?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
Post Reply