- Listing of String Functions
- Using the String Functions
- Formatting Strings
- Converting to and from Strings
- Creating Arrays
- Modifying Arrays
- Removing Array Elements
- Looping Over Arrays
- Listing of the Array Functions
- Sorting Arrays
- Navigating through Arrays
- Imploding and Exploding Arrays
- Extracting Variables from Arrays
- Merging and Splitting Arrays
- Comparing Arrays
- Manipulating the Data in Arrays
- Creating Multidimensional Arrays
- Looping Over Multidimensional Arrays
- Using the Array Operators
- Summary
Looping Over Multidimensional Arrays
So what about looping over multidimensional arrays? For example, what if your array contains two dimensions? Looping over it isn't a problem—just loop over the first index first and then the second index in an internal loop. You can do that by nesting a for loop inside another for loop:
<?php $test_scores[0][] = 95; $test_scores[0][] = 85; $test_scores[1][] = 87; $test_scores[1][] = 93; for ($outer_index = 0; $outer_index < count($test_scores); $outer_index++){ for($inner_index = 0; $inner_index < count($test_scores[$outer_index]); $inner_index++){ echo "\$test_scores[$outer_index][$inner_index] = ", $test_scores[$outer_index][$inner_index], "\n"; } } ?>
In this way, we can set the first index in the array, print out all elements by incrementing the second index, and then increment the first index to move on. Here's what you get, just as you should:
$test_scores[0][0] = 95 $test_scores[0][1] = 85 $test_scores[1][0] = 87 $test_scores[1][1] = 93
You can also use foreach loops—and in fact they're a better idea than for loops if you're using text indexes (which can't be incremented for iterating through a loop). In the following example, each time through the outer loop, we extract a new single-dimensional array to iterate over:
<?php $test_scores["Frank"]["first"] = 95; $test_scores["Frank"]["second"] = 85; $test_scores["Mary"]["first"] = 87; $test_scores["Mary"]["second"] = 93; foreach ($test_scores as $outer_key => $single_array) { . . . } ?>
And we iterate over the single-dimensional array in the inner foreach loop, as you can see in phpmultidimensional.php, Example 3-5.
Example 3-5. Looping over multidimensional arrays, phpmultidimensional.php
<HTML> <HEAD> <TITLE> Looping over multidimensional arrays </TITLE> </HEAD> <BODY> <H1> Looping over multidimensional arrays </H1> <?php $test_scores["Frank"]["first"] = 95; $test_scores["Frank"]["second"] = 85; $test_scores["Mary"]["first"] = 87; $test_scores["Mary"]["second"] = 93; foreach ($test_scores as $outer_key => $single_array) { foreach ($single_array as $inner_key => $value) { echo "\$test_scores[$outer_key][$inner_key] = $value<BR>"; } } ?> </BODY> </HTML>
The results appear in Figure 3-5. Very cool.
Figure 3-5 Looping over multidimensional arrays.