Recipe 4.1. Specifying an Array Not Beginning at Element 0


4.1.1. Problem

You want to assign multiple elements to an array in one step, but you don't want the first index to be 0.

4.1.2. Solution

Instruct array( ) to use a different index using the => syntax:

$presidents = array(1 => 'Washington', 'Adams', 'Jefferson', 'Madison');

4.1.3. Discussion

Arrays in PHP'like most, but not all, computer languages'begin with the first entry located at index 0. Sometimes, however, the data you're storing makes more sense if the list begins at 1. (And we're not just talking to recovering Pascal programmers here.)

In the Solution, George Washington is the first president, not the zeroth, so if you wish to print a list of the presidents, it's simpler to do this:

foreach ($presidents as $number => $president) {     print "$number: $president\n"; }

than this:

foreach ($presidents as $number => $president) {     $number++;     print "$number: $president\n"; }

The feature isn't restricted to the number 1; any integer works:

$reconstruction_presidents = array(16 => 'Lincoln', 'Johnson', 'Grant');

Also, you can use => multiple times in one call:

$whig_presidents = array(9 => 'Harrison', 'Tyler',[] 12 => 'Taylor', 'Fillmore');

PHP even allows you to use negative numbers in the array( ) call. (In fact, this method works for non-integer keys, too.) What you'll get is technically an associative array, although as we said, the line between numeric arrays and associative arrays is often blurred in PHP; this is just another one of these cases:

$us_leaders = array(-1 => 'George II', 'George III', 'Washington');

If Washington is the first U.S. leader, George III is the zeroth, and his grandfather George II is the negative-first.

Of course, you can mix and match numeric and string keys in one array( ) definition, but it's confusing and very rarely needed:

$presidents = array(1 => 'Washington', 'Adams', 'Honest' => 'Lincoln', 'Jefferson');

This is equivalent to:

$presidents[1]         = 'Washington';   // Key is 1 $presidents[]          = 'Adams';        // Key is 1 + 1 => 2 $presidents['Honest']  = 'Lincoln';      // Key is 'Honest' $presidents[]          = 'Jefferson';    // Key is 2 + 1 => 3

4.1.4. See Also

Documentation on array( ) at http://www.php.net/array.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net