Array
Basics
All arrays are ordered collections
of items, called elements. Each element has a value, and is identified by a key
that is unique to the array it belongs to. As we mentioned in the previous
paragraph, keys can be either integer numbers or strings of arbitrary length.
Arrays are created one of two ways.
The first is by explicitly calling the array() construct, which can be passed a
series of values and, optionally, keys:
$a = array (10, 20,
30);
$a = array (’a’ =>
10, ’b’ => 20, ’cee’ => 30);
$a = array (5 => 1,
3 => 2, 1 => 3,);
$a = array();
The first line of code above creates
an array by only specifying the values of its three elements. Since every
element of an array must also have a key, PHP automatically assigns a numeric
key to each element, starting from zero. In the second example, the array keys
are specified in the call to array()—in this case, three alphabetical keys (note
that the length of the keys is arbitrar y). In the third example, keys are
assigned “out of order,” so that the first element of the array has, in fact,
the key 5—note here the use of a “dangling comma” after the last element, which
is perfectly legal from a syntactical perspective and has no effect on the final
array. Finally, in the fourth example we create an empty array.
A second method of accessing arrays
is by means of the array operator ([]):
$x[] = 10;
$x[’aa’] = 11;
echo $x[0]; // Outputs
10
As you can see, this operator
provides a much higher degree of control than array(): in the first example, we
add a new value to the array stored in the $x var i able. Because we don’t
specify the key, PHP will automatically choose the next highest numeric key available
for us. In the second example, on the other hand, we specify the key ’aa’ ourselves.
Note that, in either case, we don’t explicitly initialize $x to be an array, which
means that PHP will automatically convert it to one for us if it isn’t; if $x
is empty, it will simply be initialized to an empty array.
Printing
Arrays
In the PHP Basics blog, we
illustrated how the echo statement can be used to output the value of an
expression—including that of a single variable. While echo is extremely useful,
it e xhibits some limitations that curb its helpfulness in certain situations.
For example, while debugging a script, one often needs to see not just the value
of an expression, but also its type. Another problem with echo is in the fact
that it is unable to deal with composite data types like arrays and objects.
To obviate this problem, PHP
provides two functions that can be used to output
a variable’s value recursively:
print_r() and var_dump(). They differ in a few key
points:
•
While both functions recursively
print out the contents of composite value, only var_dump() outputs the data
types of each value
•
Only var_dump() is capable of
outputting the value of more than one variable at the same time
•
Only print_r can return its output
as a string, as opposed to writing i t to the script’s standard output
Whether echo, var_dump() or print_r
should be used in any one given scenario is,clearly, dependent on what you are
trying to achieve. Generally speaking, echo wi ll
cover most of your bases, while
var_dump() and print_r() offer a more specialized
set of functionality that works well
as an aid in debugging.
Enumerative
vs. Associative
Arrays can be roughly divided in two
categories: enumerative and associative. Enumerative arrays are indexed using
only numerical indexes, while associative arrays (sometimes referred to as
dictionaries) allow the association of an arbitrary key to every element. In
PHP, this distinction is significantly blurred, as you can create an enumerative
array and then add associative elements to it (while still maintaining elements
of an enumeration). What’s more, arrays behave more like ordered maps and can
actually be used to simulate a number of different structures, including queues
and stacks.
PHP provides a great amount of
flexibility in how numeric keys can be assigned to arrays: they can be any
integer number (both negative and positive), and they don’t need to be
sequential, so that a large gap can exist between the indices of two consecutive
values without the need to create intermediate values to cover ever possible key
in between. Moreover, the keys of an array do not determine the order of its
elements—as we saw earlier when we created an enumerative array with keys that
were out of natural order.
When an element is added to an array
without specifying a key, PHP automatically assigns a numeric one that i s
equal to the greatest numeric key already in existence in the array, plus one:
$a = array (2 =>
5);
$a[] = ’a’; // This
will have a key of 3
Note that this is true even if the
array contains a mix of numerical and string keys:
$a = array (’4’ => 5, ’a’ =>
’b’);
$a[] = 44; // This will have a key
of 5
Multi-dimensional
Arrays
Since every element of an array can
contain any type of data, the creation of multi-dimensional arrays is very
simple: to create multi-dimensional arrays, we simply assign an array as the
value for an array element. With PHP, we can do this for one or more elements
within any array—thus allowing for infinite levels of nesting.
$array = array();
$array[] = array(
’foo’,
’bar’
);
$array[] = array(
’baz’,
’bat’
);
echo $array[0][1] .
$array[1][0];
Our output from this example is
barbaz. As you can see, to access multi-dimensional array elements, we simply
“stack” the array operators, giving the key for the specify element we wish to
access in each level.
Unravelling
Arrays
It is sometimes simpler to work with
the values of an array by assigning them to individual variables. While this
can be accomplished by extracting individual elements and assigning each of
them to a different variable, PHP provides a quick short-cut—the list()
construct:
$sql = "SELECT
user_first, user_last, lst_log FROM users";
$result = mysql_query($sql);
while (list($first,
$last, $last_login) = mysql_fetch_row($result)) {
echo "$last,
$first - Last Login: $last_login";
}
By using the list construct, and
passing in three variables, we are causing the first three elements of the array
to be assigned to those variables in order, all owing us to then simply use
those elements within our while loop.
0 Comment to " PHP Array Basics "
Post a Comment