• No results found

Array Basics

In document ZEND PHP 5 Certification (Page 66-70)

Arrays are the undisputed kings of advanced data structures in PHP. PHP arrays are extremely flexible—they allow numeric, auto-incremented keys, alphanumeric keys or a mix of both, and are capable of storing practically any value, including other arrays. With over seventy functions for manipulating them, arrays can do practically anything you can possibly imagine—and then some.

Array Basics

All arrays are ordered collections of items, calledelements. Each element has a value, and is identified by akey 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 thearray()

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

48Arrays

assigns a numeric key to each element, starting from zero. In the second example, the array keysare specified in the call toarray()—in this case, three alphabetical keys (note that the length of the keys is arbitrary). In the third example, keys are assigned “out of order,” so that the first element of the array has, in fact, the key5—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 thearray operator ([]):

$x[] = 10; $x[’aa’] = 11;

echo $x[0]; // Outputs 10

As you can see, this operator provides a much higher degree of control thanarray(): in the first example, we add a new value to the array stored in the$xvariable. 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$xto be an array, which means that PHP will automatically convert it to one for us if it isn’t; if$xis empty, it will simply be initialized to an empty array.

Printing Arrays

In thePHP Basics chapter, we illustrated how theechostatement can be used to out- put the value of an expression—including that of a single variable. Whileechois extremely useful, it exhibits some limitations that curb its helpfulness in certain sit- uations. For example, while debugging a script, one often needs to see not just the value of an expression, but also its type. Another problem withechois 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() andvar_dump(). They differ in a few key points:

• While both functions recursively print out the contents of composite value, onlyvar_dump()outputs the data types of each value

• Onlyvar_dump()is capable of outputting the value of more than one variable at the same time

• Onlyprint_rcan return its output as a string, as opposed to writing it to the script’s standard output

Whetherecho,var_dump()orprint_rshould be used in any one given scenario is, clearly, dependent onwhat you are trying to achieve. Generally speaking,echowill cover most of your bases, whilevar_dump()andprint_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. Enu- merative arrays are indexed using only numerical indexes, while associative arrays (sometimes referred to asdictionaries) 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 el- ements 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 con- secutive 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 ele- ments—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 is 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

50Arrays

$a = array (’4’ => 5, ’a’ => ’b’); $a[] = 44; // This will have a key of 5

i

Note that array keys are case-sensitive, buttype insensitive. Thus, the key’A’is differ- ent from the key’a’, but the keys’1’and1are the same. However, the conversion is only applied if a string key contains the traditional decimal representation of a num- ber; thus, for example, the key’01’isnot the same as the key1.

Multi-dimensional Arrays

Since every element of an array can containany 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 isbarbaz. 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 ele-

ments and assigning each of them to a different variable, PHP provides a quick short- cut—thelist()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 thelistconstruct, and passing in three variables, we are causing the first three elements of the array to be assigned to those variables in order, allowing us to then simply use those elements within ourwhileloop.

In document ZEND PHP 5 Certification (Page 66-70)