Nested Arrays
A nested array is an array that holds other arrays as its values. Groups of rows often take this shape, with one outer array for the groups and one inner array for each group.
A two-level structure under print_r
The outer array keys are department names. Each value is a whole array of people, and the print shows the inner arrays indented.
<?php
$company = [
"Sales" => ["Ana", "Ben"],
"Tech" => ["Cy", "Dee", "Eli"],
];
print_r($company);A nested foreach prints one line per person
The outer loop walks the departments and the inner loop walks the people of one department. The department name repeats on each line from the outer key.
<?php
$company = [
"Sales" => ["Ana", "Ben"],
"Tech" => ["Cy", "Dee", "Eli"],
];
foreach ($company as $dept => $people) {
foreach ($people as $person) {
echo $dept . " - " . $person . "\n";
}
}Counts built in the walk
The outer loop counts each inner array as it reaches it. One line prints per department with that department count.
<?php
$company = [
"Sales" => ["Ana", "Ben"],
"Tech" => ["Cy", "Dee", "Eli"],
];
foreach ($company as $dept => $people) {
echo $dept . " has " . count($people) . "\n";
}Example
<?php
$school = [
"Class A" => ["Ana", "Ben", "Cy"],
"Class B" => ["Dee", "Eli"],
];
foreach ($school as $class => $students) {
foreach ($students as $student) {
echo $class . " - " . $student . "\n";
}
echo $class . " has " . count($students) . "\n";
}Key points
- A nested array holds arrays as values inside one outer array.
- print_r shows the nesting with the inner arrays indented under their outer keys.
- A nested foreach uses one loop for the outer array and one loop for each inner array.
- The outer key is in reach inside the inner loop, so each inner value can print beside its group name.
- count on an inner array counts the values of that one group.
- A nested array holds groups as arrays, so a program can walk group by group and value by value.
In this example, a school array holds two classes and each class holds its students. The outer loop takes one class at a time. The inner loop prints one roster line per student with the class name repeated from the outer key. A count line for the class prints after its roster, so Class A reports 3 students and Class B reports 2.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the inner loop of a nested foreach walk?