Numeric arrays are arrays that are indexed by number. By default, numeric arrays are indexed by numbers starting with 0 so the last element's index is always one less than the number of elements.
You can create a numeric array two ways; by assigning a member to it with an array operator, [] or, with an a array statement. You assign a member to an array with an array operator like this:
$php_gurus[] = "Mike";
The string, "Mike" is the first element so its index is 0. You can add more members the same way:
$php_gurus[] = "Mike";
$php_gurus[] = "Sally";
$php_gurus[] = "Linda";
For that example, Mike's key is 0, Sally's 1 and Linda's 2. If you want to access a single member of the array, you use its index in the square brackets:
echo "$php_gurus[1]";
# echos Sally
You can use the same syntax to add an element to an existing array. You can also overwrite an existing element by giving a key that is already in use to the new value:
$php_gurus[] = "Mike";
$php_gurus[] = "Sally";
$php_gurus[] = "Linda";
echo "$php_gurus[0]<br />";
echo "$php_gurus[1]<br />";
echo "$php_gurus[2]<br />";
# echos Mike<br />Sally<br/>Linda
$php_gurus[1] = "Lila" # "Lila" overwrites "Sally";
echo "$php_gurus[0]<br />";
echo "$php_gurus[1]<br />";
echo "$php_gurus[2]<br />";
# echos Mike<br />Lila<br/>Linda
If you don't put a number in the array operator, the new element will become the last element in the array.
An array statement is useful when you want to assign many members at once instead of one by one. An array statement looks like this:
$php_gurus = array("Mike", "Sally", "Linda", "Lila");
|
|
|