HTML and CSS Reference
In-Depth Information
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 fol-
lows:
$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]);
The element with the index specified will be removed, and the array will decrease in size
by one element, too. The indexes of the elements with larger indexes than the one that
was removed will be reduced by one. You can also use unset() to remove elements from
associative arrays, like this:
unset($state_capitals['Texas']);
Array indexes can be specified using variables. You just put the variable reference inside
the square brackets, like this:
$i = 1;
$var = $my_array[$i];
21
This also works with associative arrays:
$str = 'dog';
$my_pet = $pets[$str];
 
Search WWH ::




Custom Search