05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter CHAPTER 5 5<br />

Arrays<br />

As we discussed in Chapter 2, <strong>PHP</strong> supports both scalar and compound data types.<br />

In this chapter, we’ll discuss one of the compound types: arrays. An array is a collection<br />

of data values, organized as an ordered collection of key-value pairs.<br />

This chapter talks about creating an array, adding and removing elements from an<br />

array, and looping over the contents of an array. There are many built-in functions<br />

that work with arrays in <strong>PHP</strong>, because arrays are very common and useful. For example,<br />

if you want to send email to more than one email address, you’ll store the email<br />

addresses in an array and then loop through the array, sending the message to the<br />

current email address. Also, if you have a form that permits multiple selections, the<br />

items the user selected are returned in an array.<br />

Indexed Versus Associative Arrays<br />

There are two kinds of arrays in <strong>PHP</strong>: indexed and associative. The keys of an<br />

indexed array are integers, beginning at 0. Indexed arrays are used when you identify<br />

things by their position. Associative arrays have strings as keys and behave more like<br />

two-column tables. The first column is the key, which is used to access the value.<br />

<strong>PHP</strong> internally stores all arrays as associative arrays, so the only difference between<br />

associative and indexed arrays is what the keys happen to be. Some array features are<br />

provided mainly for use with indexed arrays, because they assume that you have or<br />

want keys that are consecutive integers beginning at 0. In both cases, the keys are<br />

unique—that is, you can’t have two elements with the same key, regardless of<br />

whether the key is a string or an integer.<br />

<strong>PHP</strong> arrays have an internal order to their elements that is independent of the keys<br />

and values, and there are functions that you can use to traverse the arrays based on<br />

this internal order. The order is normally that in which values were inserted into the<br />

array, but the sorting functions described later let you change the order to one based<br />

on keys, values, or anything else you choose.<br />

116<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!