Team LiB
Previous Section Next Section

Basic Arrays

In PHP (and unlike most other programming languages that implement them) arrays are a means of grouping any number of different variables, regardless of type, into a single variable. Technically, arrays actually represent an ordered map that maps key values to pieces of variable data (see Figure 2.1). The contents of a value pointed to by a key in an array can be anything represented by a PHP variable; there is no limit (other than memory) imposed on the maximum number of different keys a single array can possess. There are a number of ways to declare arrays, each of which is discussed in the sections that follow.

Figure 2.1. A graphical representation of an array.


Array Syntax

In PHP, you can create an array variable in various ways. Perhaps the simplest way to implement arrays is through the following syntax:

$variable[<key expr>] = <expr>;

<key expr> is an expression that evaluates to a string or any non-negative integer, and <expr> represents the expression whose value will be associated with the key. Listing 2.1 is an example of an array $foo, which contains four keys, a, b, c, and d, assigned the integer values 1, 2, 3, and 4, respectively:

Listing 2.1. Assigning Array Values
<?php

    function assign_key() {
        return 'd';
    }
    $foo['a'] = 1;
    $foo['b'] = 2;
    $foo['c'] = 3;
    $foo[assign_key()] = 4;    /* Assigned the key value 'd' */
?>

Likewise, each of these four keys can be manipulated and used as with any other PHP variable, as shown in Listing 2.2:

Listing 2.2. Manipulating Array Values
<?php

    /* $foo['b'] now equals 1 + 3 = 4 */
    $foo['b'] = $foo['a'] + $foo['c'];
?>

NOTE

Replacing variables in strings through the use of double quotes (for example, "Value of \$myvar is $myvar") can be difficult when the variable to be evaluated is stored as a key in an array. To overcome this, braces { and } should be used to ensure that PHP will properly evaluate the string as shown:

$var = "The value of \$foo['b'] = {$foo['b']}";


If <key expr> is null or is not provided, PHP will automatically use the next integer available as the key. What integer is used as the next key is defined by the largest integer key value currently in the array. If no integers are currently being used as keys, the first key to be created will be 0. If 0 is already being used, 1 will be used, and so on. Note that PHP will not "fill in" keys. This means that if keys 1, 3, and 4 exist, PHP will create an integer key 5, regardless of the fact that key 2 is unassigned. Listing 2.3 shows an example illustrating this concept:

Listing 2.3. Autogeneration of Array Indexes
<?php

    $foo[] = "Value 1";        /* Assigned key 0 */
    $foo[] = "Value 2";        /* Assigned key 1 */
    $foo[5] = "Value 3";       /* Assigned key 5 */
    $foo[] = "Value 4";        /* Assigned key 6 */
?>

When defining an array within your script manually, using the syntax shown previously can be cumbersome. Rather than use this method, PHP provides a more formal array syntax using the array() statement. The general syntax of the array() statement is as follows:

$variable = array([mixed ...]);

In the preceding syntax, mixed represents the different key/value pairs defined in this format:

<key expr> => <value expr>,
<key expr> => <value expr> ...

For instance, the PHP code in Listing 2.4 creates the same array $foo as earlier examples using this formal syntax:

Listing 2.4. Using the array() Function
<?php

    /* Arrays $foo and $bar are equivalent arrays */
    $foo = array('a' => 1, 'b' => 2, 'c' => 3);
    $bar['a'] = 1;
    $bar['b'] = 2;
    $bar['c'] = 3;
?>

As with the less-formal counterpart, the array() statement can automatically assign keys if no key is provided. If this is desired, omit both the key expression as well as the => operator, as shown in Listing 2.5:

Listing 2.5. More Array Examples
<?php

    /* Creates an array with keys 0 through 3 */
    $myarray = array('a', 'b', 'c', 'd');

    /* Creates an array with keys 'a', 'b' and 'c with values of 1, 2 and 3
       as well as keys 0, 1 and 2 with values 'a', 'b', and 'c' */
    $myarray = array('a'=>1, 'a', 'b'=>2, 'b', 'c'=>3, 'c');

    /* Creates an array that assigns keys 1 through 7 to
       the days of the week. */
    $days = array(1=>"Sunday", "Monday", "Tuesday",
                     "Wednesday", "Thursday", "Friday", "Saturday");
?>

Multidimensional Arrays

Thus far, all your arrays have been one dimensional, meaning none of the values within the array were themselves also arrays. By definition, creating multidimensional arrays is no more difficult than assigning the value of one array key to another array itself.

As with any other array, multidimensional arrays can be created using the formal syntax (the array() statement) or by using the simplified square-bracket [] syntax shown in Listing 2.6:

Listing 2.6. Creating a Multidimensional Array
<?php

    /* Formal Syntax */
    $myarray = array('mykey'=> 'myvalue',
                     'key2'=> array(1, 2, 3, 4));
    /* Square-bracket syntax */
    $sub_array[] = 1;
    $sub_array[] = 2;
    $sub_array[] = 3;
    $sub_array[] = 4;
    $example['mykey'] = 'myvalue';
    $example['key2']  = $sub_array;

    /* Alternative method using square-brackets */
    $anotherarray['mykey'] = 'myvalue';
    $anotherarray['key2'][] = 1;
    $anotherarray['key2'][] = 2;
    $anotherarray['key2'][] = 3;
    $anotherarray['key2'][] = 4;
?>

Note that when you're working with a defined multidimensional array, key references can be stacked on top of one another to access the contents of a subarray. For example:

echo $anotherarray['key2'][0];

would access the first index of the array stored in the key called key2 of the $anotherarray variable from Listing 2.6.

Working with Arrays

Now that you understand how arrays are created, let's take a look at some of the ways arrays can be accessed and manipulated. Later, you'll learn about the actual implementation of arrays into your applications. In this section, we'll look at traversing arrays, removing elements from an array, the different ways to compare arrays, and manipulating arrays via array callback functions. I'll start first with array traversal using the foreach() statement.

Array Traversal

If you've had an opportunity to play with arrays, you'll quickly realize that there has yet to be introduced a good method of iterating through all the key/value pairs in an array with what we have discussed thus far. A partial solution is the for() loop, which can be used in conjunction with the count() function (a function that returns the number of elements in an array) to iterate through an integer-based array index, as shown in Listing 2.7:

Listing 2.7. Using count() to Iterate Through an Array
<?php

    $myarray = array('php', 'is', 'cool');

    for($i = 0; $i < count($myarray); $i++) {

      echo "The value of index $i is: {$myarray[$i]}<BR>\n";

    }
?>

Although effective, the preceding code will not work for arrays that use strings for key values (or arrays where the integer keys are not sequential). The proper way to iterate through an array is by using the foreach() statement. The syntax for the foreach() statement is as follows:

foreach( <array> as [$key_var =>] $value_var) {
    ... code for each individual array element ...
}

<array> represents the array you are iterating through, and $key_var/$value_var each represent the individual key/value pair of the current iteration. Here's how the foreach() statement works: When executed, the foreach() function will cycle through each element within <array>, storing the value of the current element in $value_var and the key value (optionally) in $key_var. These variables are then available to be used within the foreach() statement. Note that although $key_var/$value_var do contain the respective values of the current array element, modifying these values will not change the original array. To modify the contents of the original array, you can pass the $value_var variable by reference to the foreach() statement (that is, &$value_var).

Let's take a look at our earlier example using the count() function to iterate through an array, except this time you will use the foreach() statement (see Listing 2.8):

Listing 2.8. Using foreach() to Iterate Through an Array
<?php

    $myarray = array('php', 'is', 'cool');

    /* Gets both the array key and value for the current element */
    foreach($myarray as $key => $val) {
      echo "The value of index $key is: $val<BR>";
    }
    /* Only retrieves the value for the current element and ignores the key */
    foreach($myarray as $val) {
       echo "Value: $val<BR>";
    }
    ?>

In Listing 2.8, the first foreach() statement will function identically to the similar for() loop example discussed earlier. Also note that the $key variable is not required, as shown in the second foreach() example.

NOTE

Like all of PHP's control structures, an alternative syntax exists for the foreach() statement, as follows:

<?php foreach(<array> as [$key_var =>] $val): ?>
<!-- non-parsed data here //-->
<?php endforeach; ?>


Array Callbacks

Perhaps one of the more interesting things you'll notice when working with PHP arrays is their capability to be associated with callback functions. What exactly are callback functions, and how are they used with arrays? Callback functions are functions created by you (the developer), which are then called by PHP internally to perform some sort of manipulation. In this case, array callback functions are created to modify the contents of the array on a value-by-value basis. To further explain array callbacks, let's take a look at some code that implements them.

The first function that you'll be looking at is the array_map() function. This function is probably the closest thing to a general-form array callback function available to the PHP developer. It takes no less than two parameters: The first is a string (or an array if the callback is in an object) containing the name of the callback function, and each parameter to follow is the one array (or more) as shown:

array_map($callback, $array_var1 [, $array_var2, ...])

When creating your callback function, you need to know how many parameters it takes. Basically, you will need as many parameters as arrays that you plan to pass to the array_map() function. So, if you pass two arrays to array_map(), plan to have your function accept two parameters. Let's take a look at a little code shown in Listing 2.9:

Listing 2.9. Using the array_map() Function
<?php

    function my_callback($var) {

        echo "Value: $var<BR>";
        return strtoupper($var);

    }

    $myarray = array("hello", "this", "is", "a", "callback!");
    $newarray = array_map("my_callback", $myarray);

    echo "<PRE>";
    print_r($newarray);
    echo "</PRE>";
?>

NOTE

Now that we are dealing with arrays, you'll notice the use of the print_r() function. This function will output the contents of any array passed to it (even multidimensional arrays) quite nicely. However, this output is not designed to be viewed from a Web browser. Hence, wrapping it in HTML <PRE> tags is a corrective measure for browsers.


Because it is not overly obvious, let's take a look at the execution of Listing 2.9 in more detail. Ignoring the function for now, you'll see that an array $myarray has been created, followed by your call to the array_map() function. When the array_map() function is called, it traverses the entire array passed to it (in this case, $myarray) and calls the specified function my_callback(), passing it each individual value in the array and creating a new array based on what the callback function returns. Looking at your callback function, you see that it first echoes that value and then returns an all-uppercase version of it using the strtoupper() PHP function. Thus, when this script is executed, the result will be an array $newarray that is identical to the original $myarray, but with all uppercase values.

Here's the actual output produced by this script:

Value: hello
Value: this
Value: is
Value: a
Value: callback!
Array
{
    [0] => HELLO
    [1] => THIS
    [2] => IS
    [3] => A
    [4] => CALLBACK!
}

NOTE

Callback functions do not have to be user-defined functions! In fact, in the preceding example, if you were not concerned with echoing the output to the client, you could have simply defined strtoupper() as the array_map() callback function and accomplished the same task.


Likewise, the array_map() function can be used with multiple arrays in a similar fashion, as shown in Listing 2.10:

Listing 2.10. Using the array_map() Function
<?php

    function mul_callback($x, $y) {
       return $x * $y;
    }

    $numbers_1 = array (2, 4, 5);
    $numbers_2 = array (3, 4, 5);

    $answer = array_map("mul_callback", $numbers_1, $numbers_2);

    print_r($answer);
?>

In this case, you are using two arrays ($numbers_1 and $numbers_2) with the array_map() function to do some simple math and store the answer in another array. The expected output in this situation is the following:

Array
{
    [0] => 6
    [1] => 16
    [2] => 25
}

NOTE

Although it's not necessary, when you use the array_map() function with more than one array, both arrays should be the same size. If the arrays are of unequal length, the corresponding variable passed to the callback function will be empty when the shorter array runs out of elements.


Now that you have some idea of how array callback functions work, let's take a look at some other PHP array functions that use the callback model. The next function is used to essentially filter the values of an array based on the return value of your callback functionthe array_filter() function. Unlike the array_map() function already discussed, array_filter() has a slightly different (backward) syntax:

array_filter($input, $callback)

$input is the input array and $callback is the callback function to call for the array. As with array_map(), array_filter() will traverse every value within the passed array and pass it to the desired callback function. However, unlike array_map(), the callback function for the array_filter() function must return a Boolean value. If the callback function returns false, the passed parameter will not be included in the array returned by array_filter(). Of course, if the callback function returns true, the value will be included. In Listing 2.11, this concept is illustrated by using array_filter() to filter any integer in the array whose value is 10 or less:

Listing 2.11. Using the array_filter() Function
<?php

    function filter_values($value) {
        if($value > 10) return true;
        return false;
    }

    $myints = array(123,54,2,3,42,23,4,2,12);
    $filtered = array_filter($myints, "filter_values");
    print_r($filtered);
?>

As expected, when executed this script will create a new array $filtered containing the values 123, 52, 42, 23, and 12.

When dealing with the array_filter() and array_map() functions, it is useful to note that the original key relationships are maintained. This means that in Listing 2.11, the $filtered array will still have an integer key 4 whose value is 42even though some entries in the array were removed from the original $myints array. Not all functions will maintain key relationships, so it is important that the PHP manual be consulted when such behavior is desired.

    Team LiB
    Previous Section Next Section