An array is made up of elements. Each element has a key and a value. For example, an array holding information about the colors of vegetables has vegetable names for keys and colors for values, as 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 corn even if its value is blue. However, the same value can appear many times in one array. You can have green peppers, green broccoli, and green celery.
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 anything: a string, a number, true, false, or a nonscalar type such as another array.
1. Creating an Array
To create an array, use the array() language construct. Specify a comma-delimited list of key/value pairs, with the key and the value separated by =>. This is shown in Example 4-1.
Example 4-1. Creating an 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’);
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.
A shortcut for the array() language construct is a pair of square brackets (called the short array syntax). Example 4-2 creates the same arrays as Example 4-1 but with the short array syntax.
Example 4-2. Using short array syntax
$vegetables = [‘corn’ => ‘yellow’, ‘beet’ => ‘red’, ‘carrot’ => ‘orange’];
$dinner = [0 => ‘Sweet Corn and Asparagus’,
1 => ‘Lemon Chicken’,
2 => ‘Braised Bamboo Fungus’];
$computers = [‘trs-80’ => ‘Radio Shack’, 2600 => ‘Atari’, ‘Adam’ => ‘Coleco’];
You can also add elements to an array one at a time by assigning a value to a particular array key. Example 4-3 builds the same arrays as the previous two examples but does it element by element.
Example 4-3. Creating an array element by element
// 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’;
In Example 4-3, the square brackets after the array’s variable name reference a particular key in the array. By assigning a value to that key, you create an element in the array.
2. Choosing a Good Array Name
Names for variables holding arrays follow the same rules as names for any other variables. 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 a scalar value to an array (or vice versa), the old value is silently wiped out and the variable becomes the new value. In Example 4-4, $vegetables becomes a scalar, and $fruits becomes an array.
Example 4-4. 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 doesn’t work — $fruits stays 283 and the PHP engine
// issues a warning
$fruits[‘potassium’] = ‘banana’;
// But this overwrites $fruits and it becomes an array
$fruits = array(‘potassium’ => ‘banana’);
In Example 4-1, the $vegetables and $computers arrays each 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.
3. Creating a Numeric Array
PHP provides some shortcuts for working with arrays that have only numbers as keys. If you create an array with [] or array() by specifying only a list of values instead of key/value pairs, the PHP engine automatically assigns a numeric key to each value. The keys start at 0 and increase by one for each element. Example 4-5 uses this technique to create the $dinner array.
Example 4-5. Creating numeric arrays with array()
$dinner = array(‘Sweet Corn and Asparagus’,
‘Lemon Chicken’,
‘Braised Bamboo Fungus’);
print “I want $dinner[0] and $dinner[1].”;
I want Sweet Corn and Asparagus and Lemon Chicken.
Internally, the PHP engine 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. Each key is associated with its value.
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-6.
Example 4-6. Adding elements with []
// Create $lunch array with two elements
// This sets $lunch[0]
$tunch[] = ‘Dried Mushrooms in Brown Sauce’;
// This sets $lunch[1]
$tunch[] = ‘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 new 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.
4. Finding the Size of an Array
The count() function tells you the number of elements in an array. Example 4-7 demonstrates count().
Example 4-7. 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-7 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.
Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.