Specifications
If you have the information stored in file on disk, you can load the array contents directly from
the file. We’ll look at this later in this chapter under the heading “Loading Arrays from Files.”
If you have the data for your array stored in a database, you can load the array contents
directly from the database. This is covered in Chapter 10, “Accessing Your MySQL Database
from the Web with PHP.”
You can also use various functions to extract part of an array or to reorder an array. We’ll look
at some of these functions later in this chapter, under the heading “Other Array
Manipulations.”
Accessing Array Contents
To access the contents of a variable, use its name. If the variable is an array, access the con-
tents using the variable name and a key or index. The key or index indicates which stored val-
ues we access. The index is placed in square brackets after the name.
Type $products[0], $products[1], and $products[2] to use the contents of the products
array.
Element zero is the first element in the array. This is the same numbering scheme as used in C,
C++, Java, and a number of other languages, but it might take some getting used to if you are
not familiar with it.
As with other variables, array elements contents are changed by using the = operator. The fol-
lowing line will replace the first element in the array “Tires” with “Fuses”.
$products[0] = “Fuses”;
The following line could be used to add a new element—”Fuse”—to the end of the array, giv-
ing us a total of four elements:
$products[3] = “Fuses”;
To display the contents, we could type
echo “$products[0] $products[1] $products[2] $products[3]”;
Like other PHP variables, arrays do not need to be initialized or created in advance. They are
automatically created the first time you use them.
The following code will create the same $products array:
$products[0] = “Tires”;
$products[1] = “Oil”;
$products[2] = “Spark Plugs”;
If $products does not already exist, the first line will create a new array with just one element.
The subsequent lines add values to the array.
Using PHP
P
ART I
72
05 7842 CH03 3/6/01 3:42 PM Page 72