61
$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.
An identical feature is the function
array_push( )
, which pushes a new value on top of the
array stack. However, the
$foo[ ]
notation is the more traditional PHP style; it's also faster.
But, sometimes, using
array_push( )
more accurately conveys the stack nature of what
you're trying to do, especially when combined with
array_pop( )
, which removes the last
element from an array and returns it.
So far, we've placed integers and strings only inside arrays. However, PHP allows you to
assign any data type you want to an array element: booleans, integers, floating-point
numbers, strings, objects, resources,
NULL
, and even other arrays. So, you can pull arrays or
objects directly from a database and place them into an array:
while ($row = mysql_fetch_row($r)) {
$fruits[ ] = $row;
}
while ($obj = mysql_fetch_object($s)) {
$vegetables[ ] = $obj;
}
The first
while
statement creates an array of arrays; the second creates an array of objects.
See Recipe 4.3
for more on storing multiple elements per key.
To define an array not using integer keys but string keys, you can also use
array( )
, but
specify the key/value pairs with
=>
:
$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: