PHP 101 (part 3) - Chocolate Fudge And Time Machines - The Generation Gap (
Page 6 of 9 )
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:
$desserts[4] = "apricot fritters";
and the array would now look like this:
$desserts = array("chocolate mousse", "tiramisu", "apple pie", "chocolate
fudge
cake", "apricot fritters");
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
$desserts[3] = "chocolate chip cookies";
and the array would now read
$desserts = array("chocolate mousse", "tiramisu", "apple pie", "chocolate
chip
cookies", "apricot fritters");
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.