O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. Working with Arrays

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 the foreach( ) and for( ) constructs. Section 4.3 introduces the 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.

Array Basics

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.

Keys and values

Figure 4-1. Keys and values

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 corn even if its value is blue. However, the same value can appear many times in one array. You can have orange carrots, orange tangerines, and orange oranges.

Any string or number value can be an array element key such as corn, 4, -36, or Salt Baked Squid. Arrays and other nonscalar[1] values can't be keys, but they can be element values. An element value can be a string, a number, true, or false; it can also be another array.

Creating an 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[0] = 'Sweet Corn and Asparagus';
$dinner[1] = 'Lemon Chicken';
$dinner[2] = 'Braised Bamboo Fungus';

// An array called $computers with numeric and string keys
$computers['trs-80'] = 'Radio Shack';
$computers[2600] = 'Atari';
$computers['Adam'] = 'Coleco';

The array keys and values in Example 4-1 are strings (such as corn, Braised Bamboo Fungus, and Coleco) and numbers (such as 0, 1, and 2600). They are written just like other strings and numbers in PHP programs: with quotes around the strings but not around the numbers.

You can also create an array using the array( ) language construct. Example 4-2 creates the same arrays as Example 4-1.

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');

With array( ), you specify a comma-delimited list of key/value pairs. The key and the value are separated by => . The 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.

Choosing a Good Array Name

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 array called $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 scalar, and $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 $vegetables and $computers arrays store a list of relationships. The $vegetables array relates vegetables and colors, while the $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.

Creating a Numeric Array

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 the $dinner array.

Example 4-4. Creating numeric arrays with array( )

$dinner = array('Sweet Corn and Asparagus',
                'Lemon Chicken',
                'Braised Bamboo Fungus');
print "I want $dinner[0] and $dinner[1].";

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[0]
$lunch[] = 'Dried Mushrooms in Brown Sauce';
// This sets $lunch[1]
$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[3]
$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 0.

Warning

Making the first element have key 0, not key 1, is the exact opposite of how normal humans (in contrast to computer programmers) think, so it bears repeating. The first element of an array with numeric keys is element 0, not element 1.

Finding the Size of an Array

The count( ) function tells you the number of elements in an array. Example 4-6 demonstrates count( ).

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.

When you pass it an empty array (that is, an array with no elements in it), count( ) returns 0. An empty array also evaluates to false in an if( ) test expression.



[1] 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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required