We’ve already looked at arrays as if they were clusters of matchboxes glued together. Another way to think of an array is like a string of beads, with the beads representing variables that can be numbers, strings, or even other arrays. They are like bead strings, because each element has its own location and (with the exception of the first and last ones) each has other elements on either side.
Some arrays are referenced by numeric indexes; others allow alphanumeric identifiers. Built-in functions let you sort them, add or remove sections, and walk through them to handle each item through a special kind of loop. And by placing one or more arrays inside another, you can create arrays of two, three, or any number of dimensions.
Let’s assume that you’ve been tasked with creating a simple website for a local office supplies company and you’re currently working on the section devoted to paper. One way to manage the various items of stock in this category would be to place them in a numeric array. You can see the simplest way of doing so in Example 6-1.
<?php $paper[] = "Copier"; $paper[] = "Inkjet"; $paper[] = "Laser"; $paper[] = "Photo"; print_r($paper); ?>
In this example, each time you assign a value to the array
$paper
, the first empty location
within that array is used to store the value and a pointer internal to
PHP is incremented to point to the next free location, ready for future
insertions. The familiar print_r
function (which prints out the contents of a variable, array, or object)
is used to verify that the array has been correctly populated. It prints
out the following:
Array ( [0] => Copier [1] => Inkjet [2] => Laser [3] => Photo )
The previous code could equally have been written as in Example 6-2, where the exact location of each item within the array is specified. But, as you can see, that approach requires extra typing and makes your code harder to maintain if you want to insert supplies or remove supplies from the array. So, unless you wish to specify a different order, it’s usually better to simply let PHP handle the actual location numbers.
<?php $paper[0] = "Copier"; $paper[1] = "Inkjet"; $paper[2] = "Laser"; $paper[3] = "Photo"; print_r($paper); ?>
The output from these examples is identical, but you are not
likely to use print_r
in a developed
website, so Example 6-3
shows how you might print out the various types of paper the website
offers using a for
loop.
<?php $paper[] = "Copier"; $paper[] = "Inkjet"; $paper[] = "Laser"; $paper[] = "Photo"; for ($j = 0 ; $j < 4 ; ++$j) echo "$j: $paper[$j]<br>"; ?>
This example prints out the following:
0: Copier 1: Inkjet 2: Laser 3: Photo
So far, you’ve seen a couple of ways in which you can add items to an array and one way of referencing them, but PHP offers many more. We’ll get to those shortly, but first, let’s look at another type of array.
Keeping track of array elements by index works just fine, but it can require extra work in terms of remembering which number refers to which product. It can also make code hard for other programmers to follow.
This is where associative arrays come into their own. Using them, you can reference the items in an array by name rather than by number. Example 6-4 expands on the previous code by giving each element in the array an identifying name and a longer, more explanatory string value.
<?php $paper['copier'] = "Copier & Multipurpose"; $paper['inkjet'] = "Inkjet Printer"; $paper['laser'] = "Laser Printer"; $paper['photo'] = "Photographic Paper"; echo $paper['laser']; ?>
In place of a number (which doesn’t convey any useful information,
aside from the position of the item in the array), each item now has a
unique name that you can use to reference it elsewhere, as with the
echo
statement—which simply prints
out Laser Printer
. The names
(copier
, inkjet
, and so on) are called
indexes or keys and the items
assigned to them (such as “Laser Printer”) are called
values.
This very powerful feature of PHP is often used when extracting information from XML and HTML. For example, an HTML parser such as those used by a search engine could place all the elements of a web page into an associative array whose names reflect the page’s structure:
$html['title'] = "My web page"; $html['body'] = "... body of web page ...";
The program would also probably break out all the links found within a page into another array, and all the headings and subheadings into another. When you use associative rather than numeric arrays, the code to refer to all of these items is easy to write and debug.
So far, you’ve seen how to assign values to arrays by just adding
new items one at a time. Whether you specify keys, specify numeric
identifiers, or let PHP assign numeric identifiers implicitly, this is a
long-winded approach. A more compact and faster assignment method uses
the array
keyword. Example 6-5 shows both a
numeric and an associative array assigned using this method.
<?php $p1 = array("Copier", "Inkjet", "Laser", "Photo"); echo "p1 element: " . $p1[2] . "<br>"; $p2 = array('copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"); echo "p2 element: " . $p2['inkjet'] . "<br>"; ?>
The first half of this snippet assigns the old, shortened product
descriptions to the array $p1
. There
are four items, so they will occupy slots 0 through 3. Therefore, the
echo
statement prints out the
following:
p1 element: Laser
The second half assigns associative identifiers and accompanying
longer product descriptions to the array $p2
using the format
index
=>
value
. The
use of =>
is similar to the
regular =
assignment operator, except
that you are assigning a value to an index and not
to a variable. The index is then inextricably
linked with that value, unless it is reassigned a new value. The
echo
command therefore prints
out:
p2 element: Inkjet Printer
You can verify that $p1
and
$p2
are different types of array,
because both of the following commands, when appended to the code, will
cause an “undefined index” or “undefined offset” error, as the array
identifier for each is incorrect:
echo $p1['inkjet']; // Undefined index echo $p2[3]; // Undefined offset