Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.