PHP 101 (part 3) - Chocolate Fudge And Time Machines - What's That Noise? (
Page 7 of 9 )
Of course, there is a simpler way
of extracting all the elements of an array - PHP4 has a "foreach" loop designed
specifically for this purpose and similar in syntax to the Perl construct of the
same name. Here's what it looks like:
foreach ($array as $temp)
{
do this!
}
or, in English, "take each element of the array variable $array, place it in
the variable $temp, and execute the set of statements within the curly braces
on $temp"
Let's demonstrate this by re-writing the example above in terms of the "foreach"
loop:
<html>
<head>
<basefont face="Arial">
</head>
<body>
<?
//
define some array variables
$then = array("The Beatles", "Roy Orbison", "Frank
Sinatra");
$now = array("Britney Spears", "N-Sync", "Jennifer Lopez", "Blink
182");
?>
While
Mom and Dad listen to
<?
// use loop to extract and display
array elements
foreach
($then as $artist)
{
echo $artist . ", ";
}
?>
in
the living room, I'm grooving
to
<?
foreach ($now as $artist)
{
echo $artist
. ", ";
}
?>
in the basement!
</body>
</html>