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.
An array can only have one element with a given ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access