ptg16476052
658 LESSON 24: Taking Advantage of the Server
The element with the index specified will be removed, and the array will decrease in size
by one element. 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];
This also works with associative arrays:
$str = 'dog';
$my_pet = $pets[$str];
As you’ll see a bit further on, the ability to specify array indexes using variables is a
staple of some kinds of loops in PHP.
As you’ve seen, nothing distinguishes between a variable that’s an array and a variable
that holds a string or a number. PHP has a built-in function named is_array() that
returns true if its argument is an array and false if the argument is anything else. Here’s
an example:
is_array(array(1, 2, 3)); // returns true
is_array('tree'); // returns false
When PHP returns a true value, it returns the number 1. PHP
doesn’t return a value when it returns false.
NOTE
To determine whether a particular index is used in an array, you can use PHP’s array_
key_exists() function. This function is often used to do a bit of checking before refer-
ring to a particular index, for example:
if (array_key_exists("Michigan", $state_capitals) ) {
echo $state_capitals["Michigan"];
}
As mentioned previously, it’s perfectly acceptable to use arrays as the values in an array.
Therefore, the following is a valid array declaration:
$stuff = ('colors' => array('red', 'green', 'blue'),
'numbers' => array('one', 'two', 'three'));