Specifications

After we have the information as an array, we can do a number of useful things with it. Using
the looping constructs from Chapter 1, we can save work by performing the same actions on
each value in the array. The whole set of information can be moved around as a single unit.
This way, with a single line of code, all the values can be passed to a function. For example,
we might want to sort the products alphabetically. To achieve this, we could pass the entire
array to PHPs sort() function.
The values stored in an array are called the array elements. Each array element has an associ-
ated index (also called a key) that is used to access the element.
Arrays in most programming languages have numerical indexes that typically start from zero
or one. PHP supports this type of array.
PHP also supports associative arrays, which will be familiar to Perl programmers. Associative
arrays can have almost anything as the array indices, but typically use strings.
We will begin by looking at numerically indexed arrays.
Numerically Indexed Arrays
These arrays are supported in most programming languages. In PHP, the indices start at zero
by default, although you can alter this.
Initializing Numerically Indexed Arrays
To create the array shown in Figure 3.1, use the following line of PHP code:
$products = array( “Tires”, “Oil”, “Spark Plugs” );
This will create an array called products containing the three values given”Tires”, “Oil”,
and
“Spark Plugs”. Note that, like echo, array() is actually a language construct rather than
a function.
Depending on the contents you need in your array, you might not need to manually initialize
them as in the preceding example.
If you have the data you need in another array, you can simply copy one array to another using
the
= operator.
If you want an ascending sequence of numbers stored in an array, you can use the range()
function to automatically create the array for you. The following line of code will create an
array called numbers with elements ranging from 1 to 10:
$numbers = range(1,10);
Using Arrays
C
HAPTER 3
3
USING ARRAYS
71
05 7842 CH03 3/6/01 3:42 PM Page 71