Online Book Reader

Home Category

HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [218]

By Root 1332 0
foreach loop is a special version of the for loop that simplifies working with arrays. Here’s how it works.

1. Use the foreach keyword to begin the loop.

This tells PHP that you’re working with the foreach variation.

2. The first parameter is the array name.

The foreach loop is designed to work with an array, so the first parameter is the array you want to step through.

3. Create a variable to hold each element of the array.

On each pass through the loop, the $book variable will hold the current element of the $books array. Most of the time, you use a loop for an array because you want to deal with each element of the array. Using a foreach loop makes this easier.

4. Use the $book variable inside the loop.

The $book variable is ready to go. The nice thing about using foreach is you don’t have to worry about indices. The $book variable always contains the current element of the array.

You can see the results of both of these loops in Figure 4-3. To the user, there’s no difference. Both are simply text when it comes to output.

Figure 4-3: Two kinds of for loops are used to view these arrays.

Arrays and HTML

Arrays are great because they’re used to hold lists of data in your programming language. Of course, HTML already has other ways of working with lists. The

    and
      tags are both used for visual representations of lists, and the \n”;

      foreach ($books as $book){

      print ” \n”;

      } // end foreach

      print ” \n”;

      ?>

It’s a relatively simple matter to build HTML output based on arrays. To create an ordered list or unordered list, just use a foreach loop but add HTML formatting to convert the array to a list formatted in HTML:

//make the array into a numbered list

print “

    \n”;

    foreach ($books as $book){

    print “

  1. $book
  2. \n”;

    } // end foreach

    print “

\n”;

Likewise, if you want to allow the user to choose an element from an array, it’s pretty easy to set up a \n”;

foreach ($books as $book){

print “ \n”;

} // end foreach

print “ \n”;


Introducing Associative Arrays

You can use string values as keys. For example, you might create an array like this:

$myStuff = array();

$myStuff[“name”] = “andy”;

$myStuff[“email”] = “andy@aharrisbooks.net”;

Print $myStuff[“name”];

Associative arrays are different than normal (numeric-indexed) arrays in some subtle but important ways:

♦ The order is undefined. Regular arrays are always sorted based on the numeric index. You don’t know what order an associative

Return Main Page Previous Page Next Page

®Online Book Reader