In a few languages, there are both numerical and associative arrays.
But, usually the numerical array $presidents and
the associative array $presidents are distinct
arrays. Each array type has a specific behavior, and you need to
operate on them accordingly. PHP has both numerical and associative
arrays, but they don't behave independently.
In PHP, numerical arrays are associative arrays,
and associative arrays are numerical arrays. So,
which kind are they really? Both and neither. The line between them
constantly blurs back and forth from one to another. At first, this
can be disorienting, especially if you're used to
rigid behavior, but soon you'll find this
flexibility an asset.
$fruits = array('Apples', 'Bananas', 'Cantaloupes', 'Dates');
Now, the value of $fruits[2] is
'Cantaloupes'.
array( ) is very handy when you have a short list
of known values. The same array is also produced by:
$fruits[0] = 'Apples';
$fruits[1] = 'Bananas';
$fruits[2] = 'Cantaloupes';
$fruits[3] = 'Dates';
and:
$fruits[ ] = 'Apples';
$fruits[ ] = 'Bananas';
$fruits[ ] = 'Cantaloupes';
$fruits[ ] = 'Dates';
Assigning a value to an array with an empty subscript is shorthand
for adding a new element to the end of the array. So, PHP looks up
the length of $fruits and uses that as the
position for the value you're assigning. This
assumes, of course, that $fruits
isn't set to a scalar value, such as 3, and
isn't an object. PHP complains if you try to treat a
nonarray as an array; however, if this is the first time
you're using this variable, PHP automatically
converts it to an array and begins indexing at 0.
$fruits = array('red' => 'Apples', 'yellow' => 'Bananas',
'beige' => 'Cantaloupes', 'brown' => 'Dates');
Now, the value of $fruits['beige'] is
'Cantaloupes'. This is shorthand for:
$fruits['red'] = 'Apples';
$fruits['yellow'] = 'Bananas';
$fruits['beige'] = 'Cantaloupes';
$fruits['brown'] = 'Dates';
Each array can only hold one unique value for each key. Adding:
$fruits['red'] = 'Strawberry';
overwrites the value of 'Apple'. However, you can
always add another key at a later time:
$fruits['orange'] = 'Orange';