This chapter is from the book

This chapter is from the book

When simple variables are just not good enough, arrays come into play (or objects, but that’s another topic). The array section in the PHP manual, available at http://php.net/array, lists approximately 80 functions that are helpful. Therefore, this book could be filled with array-related phrases alone. However, not all of these functions are really used often. Therefore, this chapter presents the most important problems you’ll have to solve when working with arrays—and, of course, solutions for these problems.

There are two types of arrays. The names they are given differ sometimes, but usually arrays are distinguished between numeric arrays and associative arrays. The first type of array uses numeric keys, whereas the latter type can also use strings as keys.

Creating an array can be done in one of three ways:

Using the array() statement

$a = array('I', 'II', 'III', 'IV');

Successively adding values to an array using the variable name and square brackets

$a[] = 'I';
$a[] = 'II';
$a[] = 'III';
$a[] = 'IV';

Using a new square brackets syntax introduced in PHP 5.4

$a = ['I', 'II', 'III', 'IV'];

The latter method is probably the most intuitive one for Web developers because JavaScript features a very similar syntax. For the sake of backward compatibility, we will still use the first option throughout this chapter.

When using associative arrays, the same three methods can be used; however, this time keys and values must be provided:

Now, the Arabic representation of the number four can be accessed using $a['Arabic']['four'].

Of course, arrays are not only created within a script but can also come from other sources, including from HTML forms (see Chapter 5, “Interacting with Web Forms”) and from cookies and sessions (see Chapter 6, “Remembering Users (Cookies and Sessions)”). But if the array is there, what’s next? The following phrases give some pointers.

Accessing All Elements of Numeric Arrays

Looping through numeric (or indexed) arrays can most easily be done using foreach because in each iteration of the loop, the current element in the array is automatically written in a variable, as shown in the preceding code.

Alternatively, a for loop can also be used. The first array element has the index 0; the number of array indices can be retrieved using the count() function:

Both ways are equally good (or bad); though, usually, using foreach is the much more convenient way. However, there is a third possibility: The PHP function each() returns the current element in an array. The return value of each() is an array, in which you can access the value using the numeric index 1, or the string index 'value'. Using a while loop, the whole array can be traversed. The following code once again prints all elements in the array, this time using each():