Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

<?
/*
print some text explaining the output
/
print("Days left before Friday:\n");
print("

    \n");
    for($currentDate = date("U");
    date("l", $currentDate) != "Friday";
    $currentDate += (60
    60 24))
    {
    /

    print day name
    */
    print("
  1. ". date("l", $currentDate). "\n");
    }
    print("
\n");
?>


The foreach Statement


I must discuss the foreach statement here, although it is used with arrays, which are
discussed in Chapter 5. An array is a collection of values referenced by keys. The
foreach statement retrieves values from an array, one at a time. Like other looping
structures, the foreach statement may have a simple or compound statement that's
executed each time through the loop. Figure 3-6 shows the structure of a foreach
statement.


Figure 3-6. The foreach statement.

The foreach statement expects an array, the keyword as, and a definition of the
variables to receive each element. If a single value follows as, such as foreach($array
as $value), then with each turn of the loop, the variable named value will be set with
the value of the next array element. You may capture the index of the array element if
you form the foreach statement like foreach($array as $key=>$value). Keep this
statement in mind and I will revisit it in Chapter 5.


exit, die, and return


Like break, the exit statement offers a way to escape from execution, but the exit
statement stops all execution. Not even text outside of PHP tags is sent to the browser.
This is useful when an error occurs and it would be more harmful to continue executing
code than to just abort. This is often the case when preparing database queries. If the SQL
statement cannot be parsed, it makes no sense to try to execute it.

Free download pdf