Page 159 - Beginning PHP 5.3
P. 159
Chapter 6: Arrays
How It Works
After displaying the standard XHTML page header, the script starts by defining the $myBooks two-
dimensional array. Each element of the array is an associative array containing information about a
specific book.
Next, the script sets a counter variable, $bookNum, to zero and sets up the outer foreach loop. This
loop moves through each of the elements of the top-level $myBooks array. For each element, it
increments $bookNum and displays the current book number, then starts a new definition list (dl)
XHTML element.
The inner foreach loop works through the elements of the associative array stored in the current
element. For each element of the associative array, it displays the element’s key (“title”, “author”,
or “pubYear”) within an XHTML dt element, and the element’s value within a dd element. After the
inner foreach loop has run, the dl element is closed.
Once the outer loop has completed, the script ends the XHTML page.
Manipulating Arrays
You ’ ve now learned the essentials of PHP arrays: what arrays are, how to create them, how to access
their elements, how to loop through them, and how to work with multidimensional arrays.
PHP ’ s array support doesn ’ t stop there, though. As you saw with strings in Chapter 5 , PHP comes with a
huge number of array - processing functions that you can use to make arrays even more useful. In this
section you explore some of the most commonly used functions.
Sorting Arrays
One powerful feature of arrays in most languages is that you can sort the elements in any order you
like. For example, if you ’ ve just read 100 book titles from a text file into an array, you can sort the titles
alphabetically before you display them. Or you might create a multidimensional array containing customer
information, then sort the array by number of purchases to see who your most loyal customers are.
When it comes to sorting arrays, PHP provides no less than twelve functions that you can use to sort an
array. The more common ones are:
❑ sort() and rsort() – – For sorting indexed arrays
❑ asort() and arsort() – – For sorting associative arrays
❑ ksort() and krsort() – – For sorting associative arrays by key rather than by value
❑ array_multisort() – – A powerful function that can sort multiple arrays at once, or
multidimensional arrays
Sorting Indexed Arrays with sort() and rsort()
The simplest of the array sorting functions are sort() and rsort() . sort() sorts the values of the
array in ascending order (alphabetically for letters, numerically for numbers, letters before numbers),
and rsort() sorts the values in descending order. To use either function, simply pass it the array to be
121
9/21/09 9:00:16 AM
c06.indd 121
c06.indd 121 9/21/09 9:00:16 AM