Arrays are collections of related values, such as the data submitted from a form, the names of students in a class, or the populations of a list of cities. In Chapter 2, you learned that a variable is a named container that holds a value. An array is a container that holds multiple values, each distinct from the rest.
This chapter shows you how to work with arrays. Section 4.1, next, goes over fundamentals such as how to create arrays and
manipulate their elements. Frequently, you'll want to do something with each element in an
array, such as print it or inspect it for certain conditions. Section 4.2 explains how to do these things with
foreach( ) and
) constructs. Section 4.3
implode( ) and
explode( ) functions, which turn arrays into strings and strings into arrays.
Another kind of array modification is sorting, which is discussed in Section 4.4. Last, Section 4.5 explores arrays that themselves
contain other arrays.
Chapter 6 shows you how to process form data, which the PHP interpreter automatically puts into an array for you. When you retrieve information from a database as described in Chapter 7, that data is often packaged into an array.
An array is made up of elements. Each element has a key and a value. An array holding information about the colors of vegetables has vegetable names for keys and colors for values, shown in Figure 4-1.
An array can only have one element with a given key. In the vegetable color array,
there can't be another element with the key
if its value is
blue. However, the same value can
appear many times in one array. You can have orange carrots, orange tangerines, and
Any string or number value can be an array element key such as
Squid. Arrays and other nonscalar values can't be keys, but they can be element values. An element value can
be a string, a number,
false; it can also be another array.
To create an array, assign a value to a particular array key. Array keys are denoted with square brackets, as shown in Example 4-1.
Example 4-1. Creating arrays
// An array called $vegetables with string keys $vegetables['corn'] = 'yellow'; $vegetables['beet'] = 'red'; $vegetables['carrot'] = 'orange'; // An array called $dinner with numeric keys $dinner = 'Sweet Corn and Asparagus'; $dinner = 'Lemon Chicken'; $dinner = 'Braised Bamboo Fungus'; // An array called $computers with numeric and string keys $computers['trs-80'] = 'Radio Shack'; $computers = 'Atari'; $computers['Adam'] = 'Coleco';
The array keys and values in Example
4-1 are strings (such as
Coleco) and numbers (such as
2600). They are written just like other strings and numbers in PHP
programs: with quotes around the strings but not around the numbers.
Example 4-2. Creating arrays with array( )
$vegetables = array('corn' => 'yellow', 'beet' => 'red', 'carrot' => 'orange'); $dinner = array(0 => 'Sweet Corn and Asparagus', 1 => 'Lemon Chicken', 2 => 'Braised Bamboo Fungus'); $computers = array('trs-80' => 'Radio Shack', 2600 => 'Atari', 'Adam' => 'Coleco');
array( ), you specify a comma-delimited
list of key/value pairs. The key and the value are separated by
array( ) syntax is more concise when you are adding more than one
element to an array at a time. The square bracket syntax is better when you are
adding elements one by one.
Array names follow the same rules as variable names. The
first character of an array name must be a letter or number, and the rest of the
characters of the name must be letters, numbers, or the underscore. Names for arrays
and scalar variables come from the same pool of possible names, so you can't have an
$vegetables and a scalar called
$vegetables at the same time. If you assign an
array value to a scalar or vice versa, then the old value is wiped out and the
variable silently becomes the new type. In Example 4-3,
$vegetables becomes a
$fruits becomes an array.
Example 4-3. Array and scalar collision
// This makes $vegetables an array $vegetables['corn'] = 'yellow'; // This removes any trace of "corn" and "yellow" and makes $vegetables a scalar $vegetables = 'delicious'; // This makes $fruits a scalar $fruits = 283; // This makes $fruits an array and deletes its previous scalar value $fruits['potassium'] = 'banana';
In Example 4-1, the
$computers arrays store a list of relationships. The
$vegetables array relates vegetables and colors, while
$computers array relates computer names and
manufacturers. In the
$dinner array, however, we
just care about the names of dishes that are the array values. The array keys are
just numbers that distinguish one element from another.
PHP provides some shortcuts for working with
arrays that have only numbers as keys. If
you create an array with
array( ) by specifying only a list of values
instead of key/value pairs, the PHP interpreter automatically assigns a numeric key
to each value. The keys start at 0 and increase by 1 for each element. Example 4-4 uses this technique to create
Example 4-4. Creating numeric arrays with array( )
$dinner = array('Sweet Corn and Asparagus', 'Lemon Chicken', 'Braised Bamboo Fungus'); print "I want $dinner and $dinner.";
Example 4-4 prints:
I want Sweet Corn and Asparagus and Lemon Chicken.
Internally, the PHP interpreter treats arrays with numeric keys and arrays with string keys (and arrays with a mix of numeric and string keys) identically. Because of the resemblance to features in other programming languages, programmers often refer to arrays with only numeric keys as "numeric," "indexed," or "ordered" arrays, and to string-keyed arrays as "associative" arrays. An associative array, in other words, is one whose keys signify something other than the positions of the values within the array.
PHP automatically uses incrementing numbers for array keys when you create an array or add elements to an array with the empty brackets syntax shown in Example 4-5.
Example 4-5. Adding elements with [ ]
// Create $lunch array with two elements // This sets $lunch $lunch = 'Dried Mushrooms in Brown Sauce'; // This sets $lunch $lunch = 'Pineapple and Yu Fungus'; // Create $dinner with three elements $dinner = array('Sweet Corn and Asparagus', 'Lemon Chicken', 'Braised Bamboo Fungus'); // Add an element to the end of $dinner // This sets $dinner $dinner = 'Flank Skin with Spiced Flavor';
The empty brackets add an element to the array. The element has a numeric key
that's one more than the biggest numeric key already in the array. If the array
doesn't exist yet, the empty brackets add an element with a key of
function tells you the number of elements in an array. Example
Example 4-6. Finding the size of an array
$dinner = array('Sweet Corn and Asparagus', 'Lemon Chicken', 'Braised Bamboo Fungus'); $dishes = count($dinner); print "There are $dishes things for dinner.";
Example 4-6 prints:
There are 3 things for dinner.
 Scalar describes data that has a single value: a number, a piece of text, true, or false. Complex data types such as arrays, which hold multiple values, are not scalars.