Challenge - Array operations
Build a student grade board with associative arrays, foreach and array methods.
Challenge - Array operations
In this challenge you'll build a student grade board. You'll store two classes' grades as associative arrays, merge them with array_merge and use foreach to compute and print each student's average.
Each student's value is an array of scores; with a nested foreach you sum them and divide by count. This combines associative arrays, loops and arithmetic.
Exercise Build the grade board
Add "Alex" => [80, 90, 100] and "Maya" => [70, 80, 90] to the $grades1 associative array. Add "Sam" => [90, 100, 95] to $grades2. Merge with $all = array_merge($grades1, $grades2). Walk each student with an outer foreach ($all as $name => $scores); sum the scores with an inner foreach ($scores as $score); compute $avg = $total / count($scores); print echo $name . ": " . $avg . "\n".
Show example solution
Define $grades1 and $grades2 associative arrays; merge with array_merge; outer foreach walks key value, inner foreach walks scores; average = total / count.
Example solution:
<?php
// Student grade board: array_merge and two foreach loops
$grades1 = [
"Alex" => [80, 90, 100],
"Maya" => [70, 80, 90],
];
$grades2 = [
"Sam" => [90, 100, 95],
];
$all = array_merge($grades1, $grades2);
foreach ($all as $name => $scores) {
$total = 0;
foreach ($scores as $score) {
$total += $score;
}
$avg = $total / count($scores);
echo $name . ": " . $avg . "\n";
}
Test yourself
-
How does array_merge($a, $b) behave with associative arrays?
- It deletes common keys
- It merges the values of common keys
- The second array's value wins for common keys
- It cannot merge associative arrays
Show answer
The second array's value wins for common keys — Correct. In array_merge, when the same string key exists, the second array's value overwrites the first.
-
Complete the outer loop
foreach ($all ____ $name => $scores) { // inner loop and average }Show answer
foreach ($all as $name => $scores) { // inner loop and average } -
Match the array concepts
- array_merge
- merges arrays
- foreach
- iterates array
- count
- element count
- $scores as $score
- inner loop