Приглашаем посетить
Культурология (cult-lib.ru)

Arrays

Table of Contents
Previous Next

Arrays

An array is a list that can hold multiple values and is an indispensable tool in programming. An array consists of elements, each of which can hold a value. Each element is referenced by its index (or key). The most basic type of array uses integers as indices. Numerically-indexed arrays are zero-based in PHP, meaning the first element has an index of 0, the second element an index of 1, and so on. As we shall see in this chapter, some arrays have strings as their indices.

In the next few sections we'll examine the use of arrays in PHP, including array declaration, traversal, and sorting.

Initializing Arrays

There are many ways to initialize an array variable. One way is to simply start assigning values to the elements of the array variable. The code below creates an array named $aLanguages with three elements. Since we do not specify any indices, PHP by default assigns the numeric indices 0, 1, and 2:

    $aLanguages[] = "Arabic";
    $aLanguages[] = "German";
    $aLanguages[] = "Korean";

    echo($aLanguages[2]); // Prints "Korean"

To explicitly specify an index, include it between the brackets:

    $aLanguages[0] = "Arabic";
    $aLanguages[1] = "German";
    $aLanguages[2] = "Korean";

    echo($aLanguages[2]); // Prints "Korean"

Array elements do not need to be declared sequentially. The following code will create a four-element array with the indices 100, 400, 300, and 401:

    $aLanguages[100] = "Arabic";
    $aLanguages[400] = "German";
    $aLanguages[300] = "Korean";
    $aLanguages[] = "Tagalog";

    echo($aLanguages[300]); // Prints "Korean"
    echo($aLanguages[401]); // Prints "Tagalog"

Since we did not specify an index for the last element, PHP assigned the first available integer that comes after the highest index used so far: 401.

The array() construct provides an alternative way to define arrays. array() receives a comma- delimited list of values to place in the array:

    $aLanguages = array("Arabic", "German", "Korean", "Tagalog");
    echo($aLanguages[2]); // Prints "Korean"

Again, since we have not specified any indices, our array's elements are assigned the default indices. To explicitly specify an index with the array() construct, use the => operator:

    $aLanguages = array("Arabic", 3 => "German", "Korean", "Tagalog");

    echo($aLanguages[0]); // Prints "Arabic"
    echo($aLanguages[3]); // Prints "German"
    echo($aLanguages[4]); // Prints "Korean"
    echo($aLanguages[5]); // Prints "Tagalog"

As mentioned earlier in this section, array indices may also be strings:

    $aLanguages = array(
        "ar" => "Arabic",
        "de" => "German",
        "tl" => "Tagalog"
    );

    echo($aLanguages["tl"]); // Prints "Tagalog"
    $aLanguages["ko"] = "Korean";

    echo($aLanguages["ko"]); // Prints "Korean".

Looping Through Arrays

In PHP3, traversing an array typically involved a complicated implementation of the each function used in conjunction with the list construct and a while loop. PHP4 has much improved this task with the introduction of the foreach loop, which is already very familiar to Perl programmers. Its syntax is simple:

            foreach (array as [$key =>] $value) {
                statements
            }

foreach iterates once for each element of the array. On each iteration, it fills the $key variable with that element's index, and the $value variable with that element's value. These two variable names are arbitrary; the following code will work just as well:

    foreach ($aLanguages as $sIdx => $sVal) {
        echo("$sIdx is $sVal <br />");
    }

As the synopsis indicates, the index-holding variable is optional, since it often is not needed inside the loop. In this example, we omit the $key variable altogether and use a variable named $sLang instead of $value:

    echo(
        "Available Languages: <br />\n" .
        "<ul>\n"
    );

    foreach ($aLanguages as $sLang) {
        echo("<li>$sLang</li>\n");
    }

    echo("</ul>\n");

Built-In Array Functions

PHP offers a full buffet of functions that facilitate work with arrays. A handful of useful functions are described below. For a complete listing, consult the online documentation at http://www.php.net/manual/en/ref.array.php.

count()

    int count(mixed var)

count() receives an array argument and returns the number of elements. It returns zero if the variable is not set, or if it is set and contains zero elements.

in_array()


    boolean in_array(mixed needle, array haystack [, bool strict])

This function searches the haystack array for needle value and returns true if it is found in the array, or false otherwise.

reset()

    mixed reset(array array)

Every array in PHP has an internal pointer that keeps track of the current position in the array. When using constructs such as foreach, we do not need to concern ourselves with the pointer, because foreach diligently resets the pointer to the beginning of the array. However, many of the array functions, such as prev() and next() move the pointer to a new position in the array. This can then affect future calls to functions, such as array_walk(), which begins its processing wherever the pointer happens to be.

The reset() function is used to ensure that an array's pointer is placed at the first element. It returns the value of the first element:

    // Set pointer to beginning:
    reset($aLanguages);

    // Now apply my_function to every element of the array:
    array_walk($aLanguages, "my_function");

For more information about array_walk(), consult the online documentation.

sort()

    void sort(array array [, int sort_flags])

This function is used to sort the values in an array. The optional second parameter sort_flags can be used to specify how the data should be treated for the sort. The possible values are SORT_REGULAR, SORT_NUMERIC, which forces the values to be compared numerically, or SORT_STRING, which forces the values to be compared as strings.

PHP includes many sorting functions whose syntaxes are very similar to sort(). The functions differ in behavior to provide various options in the sorting process, including changes in the direction of the sort, the treatment of keys, and the comparison algorithms used. See the online documentation for arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort(), and uksort() for more information.

explode() and implode()

These two functions are officially considered string functions, but they do concern arrays. explode() is used to split a string into separate elements of an array, using a provided argument as a delimiter. implode() does the opposite: it compresses the elements of an array into a single string using a "glue" argument:


    // Turn the languages array into a single string,
    // separated by semicolons:
    $sLangString = implode('; ', $aLanguages);
    echo($sLangString);

    $sSentence = 'Never ruin an apology with an excuse';
    // Turn the sentence into an array of individual words:
    $aWords = explode(' ', $sSentence);

Predefined Arrays

Several of PHP's predefined variables are arrays. In our discussion about functions in PHP, we described the built-in $GLOBALS array which holds all of the script's global variables. Other built-in arrays contain targeted subsets of this information, such as $HTTP_POST_VARS, $HTTP_GET_VARS, and $HTTP_COOKIE_VARS, which hold the variables passed to the script via the HTTP POST method, HTTP GET method, and cookies respectively.

Multi-Dimensional Arrays

A multi-dimensional array exists when the elements of an array themselves contain arrays (which, in turn, may contain arrays of their own, and so on).

All of the same means of array initialization apply to multi-dimensional arrays, including nested array() constructs:

    $aLanguages = array(
        "Slavic" => array("Russian", "Polish", "Slovenian"),
        "Germanic" => array("Swedish", "Dutch", "English"),
        "Romance" => array("Italian", "Spanish", "Romanian")
    );

To access the deeply nested elements of a multi-dimensional array, additional sets of brackets are used. Therefore, $aLanguages["Germanic"] refers to the array containing the Germanic languages, whereas $aLanguages["Germanic"][2] refers to the third element ("English") of the nested array.

Traversing multi-dimensional arrays can be achieved with nested loops:

    foreach ($aLanguages as $sKey => $aFamily) {
        // Print the name of the language family:
        echo(
            "<h2>$sKey</h2>\n" .
            "<ul>\n" // Start the list
        );

        // Now list the languages in each family:
        foreach ($aFamily as $sLanguage) {
            echo("\t<li>$sLanguage</li>\n");
        }
        // Finish the list:
        echo("</ul>\n");
    }

With each iteration of the outer loop, the variable $sKey is populated with the name of the language family and the variable $aFamily is populated with the corresponding inner array. The inner loop then traverses the $aFamily array, placing each element's value in the variable $sLanguage.

The result is:

Click To expand

Table of Contents
Previous Next