Team LiB
Previous Section Next Section

Implementing Arrays

In total, more than 60 functions currently are dedicated to array manipulation within PHP. Although there are far too many functions to cover in this book, almost all are documented extensively within the PHP documentation available at Rather than simply reiterate the existing documentation, the focus of the remainder of this chapter will be on only the more advanced array functions and the application of those functions in scripts.

Now that you understand the formalities of the basic array, let's take a look at how arrays can be applied using the incredible number of array support functions available natively from within PHP.

Using an Array as a List

Perhaps one of the most common uses for an array is its use as a simple list. In fact, most of the examples discussed thus far have involved using the array as a simple list. In this section, we'll be looking at how a list using an array can be used to accomplish a specific taskthe automatic generation of the necessary HTML to display a group of images.

For this example, you'll define an array, $images, that will contain a list of all the different images that you will be displaying. You'll then use that array to create the necessary <IMG> HTML tags to display those images to the screen. Listing 2.12 shows the code.

Listing 2.12. Dynamic Generation of <IMG> Tags from an Array
<HEAD><TITLE>Using the array as a list</TITLE></HEAD>
    $images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
    foreach($images as $val): ?>

    <IMG SRC="/images/<?php echo $val; ?>">

<?php endforeach;?>


Taking this example a step further, how would you use an array to create a script that displays a single random image every time the script executes? To do so using an array, it is probably best that a new PHP function is introducedthe array_rand() function. The syntax of this function is as follows:

array_rand($input [, $num_desired])

As shown, the array_rand() function takes two parameters. The first $input is, as the name implies, the input array. The second optional parameter, $num_desired, is an integer identifying how many random elements to pick from the input array. If the second parameter is not specified, the function defaults to a single random element. When executed, this function returns either a scalar value representing the single key in the original array or an array list of keys picked from the original array.


In PHP, anytime a random number is required (for instance, when using the array_rand() function) the srand() function must be called to properly seed the random number generator.

With this knowledge in hand, implementing your random image script becomes trivial, as you can see in Listing 2.13:

Listing 2.13. A Random-Image Script Using array_rand()
<HEAD><TITLE>A random image script</TITLE></HEAD>
    $images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
    $rImage = array_rand($images)
<IMG SRC="<?php echo $images[$rImage]; ?>">

Using Arrays as a Sortable Table

Beyond simple lists, arrays within PHP are also very useful when you're working with and storing data that is designed to be in the form of a table. In this section, you'll learn how to implement simple tables using arrays with PHP, followed by a more complex example that is useful in developing array-based tables that can be sorted by an arbitrary column using PHP's array-sorting functions. Consider the following table:

Pet Name

Owner Name























Take a look at the preceding table; how could you implement this table using arrays in PHP? The simplest method would be to create an associative array (based on the name of each pet) whose value is another array containing the remainder of the data for a particular row, as shown in Listing 2.14:

Listing 2.14. Creating a Simple Table Using Arrays

    $petshack = array('Rosco' => array('name' => 'John',
                                       'weight' => 20,
                                       'animal' => 'Dog'),
                      'Icky' => array('name' => 'Ann',
                                      'weight' => 10,
                                      'animal' => 'Cat'),
                      'Rex' => array('name' => 'Cliff',
                                     'weight' => 3,
                                     'animal' => 'Iguana'),
                      'Buster' => array('name' => 'Amy',
                                        'weight' => 54,
                                        'animal' => 'Dog'),
                      'Delta' => array('name' => 'Hollie',
                                       'weight' => 30,
                                       'animal' => 'Dog'));

The problem with an array structure such as this is it does not lend itself well to sorting the array by a particular column. As shown in Listing 2.15, to take advantage of PHP's native sorting functionality, each column must be stored in its own separate array (keeping the key values synchronized so that index 1 for each array column corresponds to the appropriate value).

Listing 2.15. Creating a Sortable Table Using Arrays

    $petshack['name'] = array('Rosco', 'Icky', 'Rex', 'Buster', 'Delta');
    $petshack['owner'] = array('John', 'Ann', 'Cliff', 'Amy', 'Hollie');
    $petshack['weight'] = array(20, 10, 3, 54, 30);
    $petshack['animal'] = array('Dog', 'Cat', 'Iguana', 'Dog', 'Dog');

Compare Listings 2.14 and 2.15; the first thing you'll probably notice is that the second listing appears much cleaner than the original counterpart. Furthermore, because each column in the table is represented by a different PHP array, each column can also be sorted using PHP's internal array functions. To accomplish this sorting, you can use the asort() PHP function.

Although a number of sorting functions are available to the PHP developer, this particular sorting function has been chosen because of one critical detailit maintains the association of key/value pairs (see the discussion of array_filter() earlier in this chapter for more information on the importance of this). The syntax for the asort() function is as follows:

asort($input [, $sort_flag]);


The asort() function orders arrays from smallest to largest (or alphabetically from AZ). If the opposite behavior is desired, the arsort() function can be used in the same manner as asort().

$input represents the array to be sorted, and $sort_flag is an optional parameter (a constant) specifying the type of sort to perform. Note that the constants specified by the sort_flag parameter are not PHP variables. They are constant values predefined within PHP (much like what can be created using the define statement). The three possible values for the sort_flag parameter are shown in Table 2.1:

Table 2.1. asort() Constants


Compare the items normally (default).


Compare the items as numeric values.


Compare the items as string values.

When executed, the asort() function will sort the $input array as determined by sort_flag (no return value).

Implementing the asort() function to sort and maintain your table structure becomes a relatively simple task because each column of your table is stored in a separate array. Use the asort() function to sort whichever column is desired, and then use the foreach() function to display the sorted data in an HTML table, as shown in Listing 2.16, which sorts the table by the Weight column:

Listing 2.16. Sorting an Array-Based Table Using asort()
<HEAD><TITLE>Sorting Arrays</TITLE></HEAD>
<H2>Sorting Arrays using the <code>asort()</code> function</H2>

    $petshack['name'] = array('Rosco', 'Icky', 'Rex', 'Buster', 'Delta');
    $petshack['owner'] = array('John', 'Ann', 'Cliff', 'Amy', 'Hollie');
    $petshack['weight'] = array(20, 10, 3, 54, 30);
    $petshack['animal'] = array('Dog', 'Cat', 'Iguana', 'Dog', 'Dog');

    /* Sort the weights */
    asort($petshack['weight'], SORT_NUMERIC);

    <TD>Pet Name</TD>
    <TD>Pet Owner</TD>
    <TD>Pet Weight</TD>
    <TD>Type of Animal</TD>

    foreach($petshack['weight'] as $key=>$weight) {
        echo "<TR>";
        echo "<TD>{$petshack['name'][$key]}</TD><TD>{$petshack['owner'][$key]} </TD>";
        echo "<TD>{$weight}</TD><TD>{$petshack['animal'][$key]}</TD>";
        echo "</TR>";


By changing the array passed to the asort() function (and also changing the foreach() function to loop through the array that had been sorted), this script can be modified with little difficulty to sort based on any of the four columns.

Using Arrays as a Lookup Table

Now that you have an idea of how to use arrays to develop a simple table and how array tables can be designed to provide for the maximum flexibility when dealing with sorting, let's take a look at a different type of tablethe lookup table. Unlike the tables discussed in the previous section of this chapter, a lookup table is not designed to be displayed to the user. Rather, it can be described as a reference table created and used by the PHP script to make a script more efficient or simplify a task. In this section, you'll be looking at a simple application of a lookup table. Specifically, you'll see how to implement a lookup table to create cryptograms (a puzzle game).

Although not as common in the newspaper today, cryptograms can be found in almost any puzzle book from your local supermarket. For those who are not familiar with them, the premise is quite simple: for a given string, replace every character (for instance, the letter A) with a different character. The challenge is then to take the encoded message and determine what the original message was. Although there are various ways to go about creating a cryptogram-generation script, we'll do so using a number of array functions starting with range().

In PHP, the range() function is used to create arrays that contain a specified range of numbers or letters. The syntax for range is as follows:

range(mixed $low, mixed $high)

$low represents the starting point of the range, and $high represents the end. As I have already alluded, these parameters can be numbers (that is, 1 through 10) or letters (that is, d through w). When executed, range() will return an integer-indexed array containing every number or letter between $low and $high. This function will be used to create an array containing all the letters in the alphabet, as well as the letters used to encode the cryptogram.

The second function that requires an introduction is the one actually responsible for determining how the letters are encoded in the final cryptogramthe shuffle() function. This function is similar to the array_rand() function discussed earlier in the chapter, with one significant difference. Instead of creating a new array randomly based on another array, the shuffle() function actually randomizes the contents of an array. The very simple syntax of the shuffle() is as follows:


Another function we'll need for this example is one that swaps the key/value pairs (so the keys are values, and the values are keys). To accomplish this, you'll use the array_flip() function, which also has a simple syntax:


$input represents the array to flip, and when executed, array_flip() returns the new (flipped) array.

Finally, take a look at your first search function in PHPthe in_array() function. This function takes two parameters (the value being searched for and the array to search) and returns a Boolean value indicating whether the particular value was found as described in the syntax that follows:

in_array($needle, $haystack [, $strict])

Note that the in_array() function also provides a third optional parameter, $strict. This optional Boolean value (false by default) determines whether the value specified in the $needle parameter must match not only the value, but the data type found in the corresponding array, $haystack. Thus, in an array with the string value 10, searching for the integer value 10 would return true. However, by setting the $strict parameter to true the same operation would return false.

Now that you have been introduced to the new functions being used in this example, let's take a look at the first portion of the cryptogram script, as shown in Listing 2.17:


In Listing 2.17, the closing PHP tag ?> is intentionally omitted because it is only a fragment of the script.

Listing 2.17. A Cryptogram Generator Using PHP Arrays (Part 1)

    /* Initialize the random number generator */
    srand((double)microtime() * 1000000);

    $message = "This is my super secret message!";
    $message = strtoupper($message);

    /* Create an alphabet array whose keys are the letters A-Z, and whose
       values are the numbers 0 - 25 respectively */
    $alphabet = array_flip(range('A', 'Z'));
    $cryptogram = range('A', 'Z');

    /* Randomize the lookup table used for the cryptogram generation */

As shown in Listing 2.17, the first step in your cryptogram script is the initialization of the random-number generator. As was the case with array_rand(), the shuffle() function requires this to function properly. The $message variable (which represents the actual string you are encoding) is then initialized and converted to uppercase using the strtoupper() function. Using a combination of the range() function coupled with the array_flip() function, we create an associative array, $alphabet, which has key values for every letter in the alphabet and associates these values with the integers 0 tHRough 25. Complementing the $alphabet variable is the $cryptogram variable, which is initialized with 26 values representing the letters of the alphabet. The $cryptogram variable will be used to encode the message into the final cryptogram.

With all the initialization complete, you randomize your cryptogram lookup table using the shuffle() function discussed earlier and begin encoding your cryptogram (see Listing 2.18):

Listing 2.18. A Cryptogram Generator Using PHP Arrays (Part 2)
$encoded = "";

/* Cycle through each character of the message to encode */
for($i = 0; $i < strlen($message); $i++) {

    $char = $message[$i];

    /* Determine if the current character is encodable
    by searching for it in the $cryptogram lookup table */
    if(!in_array($char, $cryptogram)) {

     /* if character is not encodable, copy straight to
        the encoded string */
     $encoded .= $char;

    } else {

     /* if the character is encoded, replace it with the
        matching character from $cryptogram */
         $encoded .= $cryptogram[$alphabet[$char]];



    echo $encoded;


Although not arrays, a string within PHP can behave like an array; it allows the developer to access a single character from the string by referencing it using the square-bracket syntax shown in Listing 2.18. Note that although strings can behave as arrays, they cannot be used with array manipulation statements, such as foreach(), or array functions.

With all the initialization complete, the next step in the script is to cycle through each individual character within the message to encode using a for() loop starting from 0 to the length returned by the strlen() function. The strlen() function returns the length of the provided string (strings are discussed in detail in Chapter 1). Because a number of cryptogram-generated characters don't translate (punctuation, whitespace, and so on) it is necessary to check to see that each character in the message being encoded exists prior to attempting to encode it. To do so, use the in_array() function to ensure that the character exists within the $cryptogram lookup table. If there is no translation available for the particular character (meaning in_array() returned false) it is passed straight into the encoded message stored in the $encoded variable. Otherwise, the character is translated based on the $cryptogram array. However, because the $cryptogram array's keys are not characters (recall that they are integer values 025) the $alphabet array is used to retrieve the particular integer value for the given character.

After the message is processed character-by-character, $encoded contains the complete cryptogram for the message (which is then displayed to the client). Because this script generates a completely new cryptogram every time it is executed, it is impossible to display the exact output. However, when this script was executed, my output was the following:


Converting from Strings to Arrays and Back

As introduced in Chapter 1, you can use a number of methods for processing strings in PHP. One very common use of arrays is processing a list of items represented as a string, such as the following:

John Coggeshall, Max Smith, Mary Johnston

When processing such a list, PHP provides a function that allows you to tokenize (separate) string values by a constant separatorthe explode() function with the following syntax:

explode($separator, $string [, $limit]);

$separator is the string that will represent the separator that $string will be broken into. Optionally, you can also pass the $limit parameter, which represents the maximum number of splits to occur. When executed, the explode() function breaks a string into individual array elements using the value of $separator to indicate where each split will occur. Using our earlier string list, to break apart each name the comma character (,) would be used as shown in Listing 2.19:

Listing 2.19. Using the explode() Function

    $input_string = "John Coggeshall, Max Smith, Mary Johnston";

    $pieces = explode(",", $input_string);

    echo "Names in List: <BR/>\n";
    foreach($pieces as $name) {
        echo trim($name) . "<BR/>\n";


Conversely, PHP also provides a function that will take all of the individual elements within an array and create a string from them. This function is the implode() function and has the following syntax:

implode($glue, $pieces);

$glue is the string used to "glue" each element of the array specified by $pieces together. Listing 2.20 uses this function to re-create our original string after it has been exploded:

Listing 2.20. Using the implode() Function

    $input_array = array("John Coggeshall",
                         "Max Smith",
                         "Mary Johnston");

    $orig_string  = implode(", ", $input_array);


    Team LiB
    Previous Section Next Section