Chapter 4. Groups of Data: 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.
This chapter shows you how to work with arrays. The next section, “Array Basics”, 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. “Looping Through Arrays” explains how to do these
things with the foreach() and for() constructs. “Modifying Arrays” 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
“Sorting Arrays”. Finally, “Using Multidimensional Arrays” explores arrays that contain other arrays.
Working with arrays is a common PHP programming task. Chapter 7 shows you how to process form data, which the PHP engine automatically puts into an array for you. When you retrieve information from a database as described in Chapter 8, that data is often packaged into an array. Being comfortable with arrays makes it easy for you to manipulate these kinds of data.
Array Basics
An array is made up of elements. Each element has a key and a value. For example, an array holding ...