Jump to content

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


canadian_angel

Recommended Posts

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

 

 

<!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>

 

You're not using the correct variables for the foreach statement. It should be

// Print each quotation from quotes.txt.
        foreach ($data as $quote) {
            print "<p>$quote</p>\n;";
        }

 

$data contains the array of quotes.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.