Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

The PHP Language 657

24


1, and the index of blue is 2. You can reference an element of an array using its index,
like this:


$color = $colors[1];


By the same token, you can assign values to specific elements of an array, too, like this:


$colors[2] = 'purple';


You can also use this method to grow an array, as follows:


$colors[3] = 'orange';


What happens if you skip a few elements when you assign an item to an array, as in the
following line?


$colors[8] = 'white';


In this case, not only will element 8 be created, but elements 4 through 7 will be created,
too. If you want to add an element onto the end of an array, you just leave out the index
when you make the assignment, like this:


$colors[] = 'yellow';


In addition to arrays with numeric indexes, PHP supports associative arrays, which have
indexes supplied by the programmer. These are sometimes referred to as dictionaries or
as hashes. Here’s an example that shows how they are declared:


$state_capitals = array(
'Texas' => 'Austin',
'Louisiana' => 'Baton Rouge',
'North Carolina' => 'Raleigh',
'South Dakota' => 'Pierre'
);


When you reference an associative array, you do so using the keys you supplied, as
follows:


$capital_of_texas = $state_capitals['Texas'];


To add a new element to an associative array, you just supply the new key and value, like
this:


$state_capitals['Pennsylvania'] = 'Harrisburg';


If you need to remove an element from an array, just use the built-in unset() function,
like this:


unset($colors[1]);

Free download pdf