4.1. Specifying an Array Not Beginning at Element 0
Problem
You want to assign multiple elements to an array in one step, but you don’t want the first index to be 0.
Solution
Instruct array( )
to use a different index using the
=> syntax:
$presidents = array(1 => 'Washington', 'Adams', 'Jefferson', 'Madison');
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:[3]
$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
noninteger 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access