Chapter 7. Arrays

Arrays are ordered maps—constructs that associate specific values to easily identified keys. These maps are effective ways to build both simple lists and more complex collections of objects. They’re also easy to manipulate—adding or removing items from an array is straightforward and supported through multiple functional interfaces.

Types of Arrays

There are two forms of arrays in PHP—numeric and associative. When you define an array without explicitly setting keys, PHP will internally assign an integer index to each member of the array. Arrays are indexed starting with 0 and increase by steps of 1 automatically.

Associative arrays can have keys of either strings or integers, but generally use strings. String keys are effective ways to “look up” a particular value stored in an array.

Arrays are implemented internally as hash tables, allowing for effective direct associations between keys and values. For example:

$colors = [];
$colors['apple']  = 'red';
$colors['pear']   = 'green';
$colors['banana'] = 'yellow';

$numbers = [22, 15, 42, 105];

echo $colors['pear']; // green
echo $numbers[2]; // 42

Unlike simpler hash tables, though, PHP arrays also implement an iterable interface allowing you to loop through all of their elements one at a time. Iteration is fairly obvious when keys are numeric, but even with associative arrays, the elements have a fixed order because they’re stored in memory. Recipe 7.3 details different ways to act on each element in both types of ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.