Using Arrays in PHP
Read PHP and MySQL® Web Development, Fourth Edition or more than 24,000 other books and videos on Safari Books Online. Start a free trial today.
This chapter shows you how to use an important programming constructarrays. The variables that we looked at in the previous chapters are scalar variables, which store a single value. An array is a variable that stores a set or sequence of values. One array can have many elements. Each element can hold a single value, such as text or numbers, or another array. An array containing other arrays is known as a multidimensional array.
PHP supports both numerically indexed and associative arrays. You will probably be familiar with numerically indexed arrays if you've used any programming language, but unless you use PHP or Perl, you might not have seen associative arrays before. Associative arrays let you use more useful values as the index. Rather than each element having a numeric index, they can have words or other meaningful information.
We will continue developing the Bob's Auto parts example using arrays to work more easily with repetitive information such as customer orders. Likewise, we will write shorter, tidier code to do some of the things we did with files in the previous chapter.
Key topics covered in this chapter include
Numerically indexed arrays
Associative arrays
Multidimensional arrays
Sorting arrays
What Is an Array?
We looked at scalar variables in Chapter 1, "PHP Crash Course." A scalar variable is a named location in which to store a value; similarly, an array is a named place to store a set of values, thereby allowing you to group scalars.
Bob's product list will be the array for our example. In Figure 3.1, you can see a list of three products stored in an array format and one variable, called $products, which stores the three values. (We'll look at how to create a variable like this in a minute.)
Figure 3.1 Bob's products can be stored in an array.
After we have the information as an array, we can do a number of useful things with it. Using the looping constructs from Chapter 1, we can save work by performing the same actions on each value in the array. The whole set of information can be moved around as a single unit. This way, with a single line of code, all the values can be passed to a function. For example, we might want to sort the products alphabetically. To achieve this, we could pass the entire array to PHP's sort() function.
The values stored in an array are called the array elements. Each array element has an associated index (also called a key) that is used to access the element.
Arrays in most programming languages have numerical indexes that typically start from zero or one. PHP supports this type of array.
PHP also supports associative arrays, which will be familiar to Perl programmers. Associative arrays can have almost anything as the array indices, but typically use strings.
We will begin by looking at numerically indexed arrays.