Chapter 5. ArraysAs we discussed in Chapter 2, PHP supports both scalar and compound data types. In this chapter, we'll discuss one of the compound types: arrays. An array is a collection of data values, organized as an ordered collection of key-value pairs.
This chapter talks about creating an array, adding and removing elements from an array, and looping over the contents of an array. There are many built-in functions that work with arrays in PHP, because arrays are very common and useful. For example, if you want to send email to more than one email address, you'll store the email addresses in an array and then loop through the array, sending the message to the current email address. Also, if you have a form that
|
5.1 Indexed Versus Associative ArraysThere are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables. The first column is the key, which is used to access the value.
PHP internally stores all arrays as associative arrays, so the only difference between associative and indexed arrays is what the keys happen to be. Some array features are provided
PHP arrays have an internal order to their elements that is independent of the keys and values, and there are functions that you can use to traverse the arrays based on this internal order. The order is normally that in which values were inserted into the array, but the sorting functions described later let you change the order to one based on keys, values, or anything else you choose. |
5.2 Identifying Elements of an Array
You can access specific values from an array using the array variable's
$age['Fred'] $shows[2]
The key can be either a string or an integer. String values that are equivalent to integer
You don't have to quote single-word strings. For instance,
$age['Fred']
is the same as
$age[Fred]
. However, it's
define('index',5);
echo $array[index]; // retrieves $array[5], not $array['index'];
You must use quotes if you're using interpolation to build the array index: $age["Clone$number"] However, don't quote the key if you're interpolating an array lookup: // these are wrong print "Hello, $person['name']"; print "Hello, $person["name"]"; // this is right print "Hello, $person[name]"; |
5.3 Storing Data in ArraysStoring a value in an array will create the array if it didn't already exist, but trying to retrieve a value from an array that hasn't been defined yet won't create the array. For example: // $addresses not defined before this point echo $addresses[0]; // prints nothing echo $addresses; // prints nothing $addresses[0] = 'spam@cyberpromo.net'; echo $addresses; // prints "Array" Using simple assignment to initialize an array in your program leads to code like this: $addresses[0] = 'spam@cyberpromo.net'; $addresses[1] = 'abuse@example.com'; $addresses[2] = 'root@example.com'; // ... That's an indexed array, with integer indexes beginning at 0. Here's an associative array: $price['Gasket'] = 15.29; $price['Wheel'] = 75.25; $price['Tire'] = 50.00; // ... An easier way to initialize an array is to use the array( ) construct, which builds an array from its arguments:
$addresses = array('spam@cyberpromo.net', 'abuse@example.com',
'root@example.com');
To create an associative array with array( ) , use the => symbol to separate indexes from values:
$price = array('Gasket' => 15.29,
'Wheel' => 75.25,
'Tire' => 50.00);
Notice the use of whitespace and alignment. We could have bunched up the code, but it wouldn't have been as easy to read:
$price = array('Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00);
To construct an empty array, pass no arguments to array( ) : $addresses = array( );
You can specify an initial key with
=>
and then a list of values. The values are inserted into the array starting with that key, with
$days = array(1 => 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
// 2 is Tuesday, 3 is Wednesday, etc.
If the initial index is a non-numeric string, subsequent indexes are integers beginning at 0. Thus, the following code is probably a mistake:
$whoops = array('Friday' => 'Black', 'Brown', 'Green');
// same as
$whoops = array('Friday' => 'Black', 0 => 'Brown', 1 => 'Green');
5.3.1 Adding Values to the End of an ArrayTo insert more values into the end of an existing indexed array, use the [] syntax:
$family = array('Fred', 'Wilma');
$family[] = 'Pebbles'; // $family[2] is 'Pebbles'
This construct assumes the array's indexes are
$person = array('name' => 'Fred');
$person[] = 'Wilma'; // $person[0] is now 'Wilma'
5.3.2 Assigning a Range of ValuesThe range( ) function creates an array of consecutive integer or character values between the two values you pass to it as arguments. For example:
$numbers = range(2, 5); // $numbers = array(2, 3, 4, 5);
$letters = range('a', 'z'); // $numbers holds the alphabet
$reversed_numbers = range(5, 2); // $numbers = array(5, 4, 3, 2);
Only the first letter of a string argument is used to build the range:
range('aaa', 'zzz') /// same as range('a','z')
5.3.3 Getting the
|