ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP Foundations

Arrays in PHP: Part 2

06/21/2001

Today we'll continue our discussion of arrays in PHP including the use of associative and multidimensional arrays.

In my last article, we introduced a new array data type in PHP and covered its fundamentals. Today we'll dive deeper into arrays and introduce a type of array called an associative array and a more complex type of array -- the multidimensional array.

Associative arrays

When we last discussed arrays, we described how arrays could be used and only deal with indexes based on integer numbers (1,2,3,etc). This week we'll introduce another type of array -- the associative arrays. Associative arrays are identical to any other type of array with one major difference -- their index values. In Associative arrays index values are not limited to simple integer values but can also be strings. For example, in an associative array the index "foo" can be used to store the value "bar". Thankfully, declaring and working with Associative arrays is identical to working with any other type of array. Here's an example:

<?php
  $myarray_1 = array("foo"=>"bar");
  $myarray_2["foo"] = "bar";
?>

As you can see, working with associative arrays and integer indexed arrays is nearly identical. But how can we use associative arrays to our advantage? With such flexibility, we are able to assign any string (such as a name) with any other string or data type (such as a phone number or e-mail address). Another example would be assigning meaningless error messages generated by your web site to a more useful description. These are just two examples of the usefulness of associative arrays. Next, we'll discuss ways to embed arrays within other arrays to create what is called a multidimensional array.

Multidimensional arrays

As we just stated, a multidimensional array is an array that contains at least one other array as the value of one of the indexes. An example of a multidimensional array would be an array $foo that has values for the indexes 1 through 5 with index value 2 containing another array. Creating and working with multidimensional arrays can be done a number of ways -- all of which we introduced in part 1 of this series. For example, in part 1 we discussed how to create a single-dimensional array using the array statement as follows:

<?php
  $foo = array(0=>"abc",
               1=>"def",
               2=>"ghi");
?>

Where the three indexes 0,1, and 2 are associated with different letters in the alphabet. In a multidimensional array, we can simply replace one of those associations with one that points to an array rather than a string constant. For example:

<?php

  $emails = array("john"=>"john@coggeshall.org",
                  "dan"=>"dan@somewhere.com",
                  "rachel"=>"rachel@coggeshall.org");

  $foo = array(0=>"abc",
               1=>$emails,
               2=>"ghi");
?>

As you can see, we have replaced index 1 in our $foo array with the variable $emails (also an array) and therefore creating a multidimensional array. Also note that we could have simply appended $foo automatically using the syntax we introduced in part 1 of the series:

<?php	$foo[] = $emails; ?>

Using the above would have created a new integer index 3 and associated with it the array $emails. Once we have created this association, we can add a whole new index to our $emails array that is embedded within $foo by the following syntax:

<?php $foo[3]['steve'] = "steve@somewhere.com";

Also in PHP Foundations:

Using MySQL from PHP, Part 2

Using MySQL from PHP

MySQL Crash Course, Part 3

MySQL Crash Course, Part 2

MySQL Crash Course

Because index 3 of $foo is an array, we can reference that array by appending an additional set of brackets to the $foo variable. In the above example, the result would be a fourth entry with the index value of "steve" and data value of "steve@somewhere.com" being created in the array located at the 3rd index of the array $foo. It's a little confusing, but the best way to look at it is to remember that $foo[3] is really no different than $foo_3 (a normal variable name) in practice. When you reference an index of an array directly, the rest of the contents of the array are inconsequential and is best to disregard when trying to visualize complex multidimensional arrays.

More on working with and getting data from arrays

To wrap up our two-part series on arrays, we'll briefly touch on some functions that will help you work with arrays (they will be discussed further in future issues), and introduce a new control structure that will greatly enhance the power of arrays in PHP. We'll start with some useful functions available to PHP developers to help them gather information and then introduce our new control structure (foreach).

As we already mentioned, PHP has a wealth of pre-programmed functions for manipulating, analyzing, and processing arrays built into the language. For a complete list of these functions, please visit the PHP web manual reference for arrays. Almost all of them are very useful under the right circumstances so we'll only discuss the ones here that are necessary for just about any application of arrays in PHP. These functions are: is_array(), in_array(), and count().

Useful array functions

Here are some useful functions to get you started working with arrays:

For full documentation on these functions and examples of their use, please consult the PHP manual.

A new control structure: foreach

Of all of the control structures available to developers in PHP, foreach is the only one specifically for use with arrays. In functionality, it is very similar to the for statement but doesn't look much like one in syntax. Its purpose is to provide a quick and easy way for developers to traverse the contents of an array (both integer indexed and associative) and process each element within the array. For example, let's say you have an integer-indexed array with an unknown number of elements that you would like to print the values for. This can be accomplished of course through the use of the for statement and our newly-found count() statement as shown below:

<?php
  for($i = 0; $i < count($myarray); $i++) {
    echo $myarray[$i];
  }
?>

There is nothing wrong with this style. However, what if the array was an associative array rather than integer-based? In such circumstances, complex while statements coupled with at least two more functions could produce the same results however we have a better solution: the foreach statement. The syntax for the foreach statement is as follows:

foreach($array_val as [$key_val =>] $value) {
	...
}

It also has a syntax simliar to the for() endfor; syntax:

foreach($array_val as [$key_val =>] $value):
   ...
endforeach;

where $array_val is the array, $key_val is the variable assigned to store the current index, and $value stores the actual value associated with that index.

How it works

Let's consider the following two samples of the foreach statement:

<?php
  $myarray = array("foo"=>"bar",
                       0=>5,
              "mynumber"=>12e3);
  foreach($myarray as $value) {
    echo "The value is $value<br />";
  }
  echo "<br />";
  foreach($myarray as $key=>$value) {
    echo "The value of index $key is $value<br />";
  }
?>

In this code fragment, we create a simple array $myarray that has three values in it. The first is a string-based key "foo" with a value of "bar", the second is a integer-based key of 0 with a value of 5, and the third is a string-based key of "mynumber" with a value of "12e3" (or 12,000 in standard notation). We then use both syntaxes of the foreach statement and echo the results. When this script is executed, we'll get the following output:

The value is bar
The value is 5
The value is 12000
The value of index foo is bar
The value of index 0 is 5
The value of index mynumber is 12000

When we compare the two foreach statement outputs, we can see that both of them traversed the entire array and stored the value stored at each index of the array in the variable $value which we then output to the screen.

In the second foreach statement however, we specified a variable to be used to store the value of the index as well as the value at that index. The result was we were able to not only traverse the array for all of its values, but also retrieve and maintain the association between the indexes of those values. This is a very powerful and useful tool when dealing with arrays that will allow you to quickly and easily process each individual item within any type of array regardless of its type of index. It is strongly recommended that the foreach statement be used in all array traversals (instead of a for loop).

Note: Although we used the values $key and $value in our foreach example, the variable names themselves can be any valid variable name within PHP (provided of course that it is not being used elsewhere in your script).

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.