chap3_0672323257
- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
Chapter 3: Using Arrays
"Art strives for form, and hopes for beauty."
George Bellows
3.0 Introduction
When I go to the grocery store, I go with a list of what I want to buy. A sample grocery list might be
In PHP, we would probably specify that grocery list as an array, or a list of scalars, with each element of the array containing an item on the grocery list:
$grocery_array = array ("eggs", "milk", "turkey", "curry");
Then if I wanted to print out an element of that array, I would reference it by its number in the array. For example, the following would print out turkey:
print $grocery_array[2];
NOTE
As with almost all programming languages, PHP arrays are indexed from 0 instead of 1. Therefore, an index of 2 refers to the third element of the array.
Arrays are one of the most powerful parts of the PHP language; they allow for the organization of related data, and quick access to that data. In this chapter and the next, we will discuss in depth how to efficiently manipulate arrays, as well as a few tricks of the trade.