HomePHP Page 6 - PHP 101 (part 3) - Chocolate Fudge And Time Machines
The Generation Gap - PHP
After teaching you the fundamentals of form processing, PHP 101 returns with an explanation of WHILE, FOR and FOREACH loops, those PHP constructs that can save you hours of unnecessary HTML coding. Also included: array variables, the auto-increment operator, and some yummy desserts.
You can add elements to the array in a similar manner - for example, if you wanted to add the element "apricot fritters" to the $desserts array, you would use this:
In order to modify an element of an array, you would simply assign a new value
to the corresponding scalar variable. If you wanted to replace "chocolate fudge cake" with "chocolate chip cookies", you'd simply use
PHP arrays can store both string and numeric data - in fact, the same array can
store both types of data, a luxury not available in many other programming languages.
How about a quick example?
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<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
for ($x=0; $x<sizeof($then);
$x++)
{
echo $then[$x] . ", ";
}
?>
in the living room, I'm grooving to
<?
for
($y=0; $y<sizeof($now); $y++)
{
echo $now[$y] . ", ";
}
?>
in the basement!
</body>
</html>
And here's what you'll see:
While Mom and Dad listen to The Beatles, Roy Orbison, Frank Sinatra, in the
living
room, I'm grooving to Britney Spears, N-Sync, Jennifer Lopez, Blink
182, in the
basement!
In this case, we've first defined two arrays, and then used the "for" loop to
run through each one, extract the elements using the index notation, and display them one after the other. Note our usage of the sizeof() function - this function is typically used to return the size or length of an array variable, and is used here to ensure that the loop iterates as many times as there are elements in each array.