Specifications
Using Loops to Access the Array
Because the array is indexed by a sequence of numbers, we can use a for loop to more easily
display the contents:
for ( $i = 0; $i<3; $i++ )
echo “$products[$i] “;
This loop will give similar output to the preceding code, but will require less typing than man-
ually writing code to work with each element in a large array. The ability to use a simple loop
to access each element is a nice feature of numerically indexed arrays. Associative arrays are
not quite so easy to loop through, but do allow indexes to be meaningful.
Associative Arrays
In the products array, we allowed PHP to give each item the default index. This meant that the
first item we added became item 0, the second item 1, and so on. PHP also supports associa-
tive arrays. In an associative array, we can associate any key or index we want with each value.
Initializing an Associative Array
The following code creates an associative array with product names as keys and prices as
values.
$prices = array( “Tires”=>100, “Oil”=>10, “Spark Plugs”=>4 );
Accessing the Array Elements
Again, we access the contents using the variable name and a key, so we can access the infor-
mation we have stored in the prices array as
$prices[ “Tires” ], $prices[ “Oil” ], and
$prices[ “Spark Plugs” ].
Like numerically indexed arrays, associative arrays can be created and initialized one element
at a time.
The following code will create the same $prices array. Rather than creating an array with
three elements, this version creates an array with only one element, and then adds two more.
$prices = array( “Tires”=>100 );
$prices[“Oil”] = 10;
$prices[“Spark Plugs”] = 4;
Here is another slightly different, but equivalent piece of code. In this version, we do not
explicitly create an array at all. The array is created for us when we add the first element to it.
$prices[“Tires”] = 100;
$prices[“Oil”] = 10;
$prices[“Spark Plugs”] = 4;
Using Arrays
C
HAPTER 3
3
USING ARRAYS
73
05 7842 CH03 3/6/01 3:42 PM Page 73