3v4l.org

run code in 300+ PHP versions simultaneously
<?php $teams = [ 1 => [ 'AREA I' => [ 'blue' => 30, 'green' => 25, ], 'AREA II' => [ 'blue' => 15, ], ], 2 => [ 'AREA I' => [ 'blue' => 40, ], ], ]; $filterSets = [ [], [1], [2], [null, 'AREA I'], [null, 'AREA II'], [null, null, 'blue'], [null, null, 'green'], [null, 'AREA I', 'blue'], ]; function sumViaPath(array $array, array $path): int { $sum = 0; $filterKey = $path ? array_shift($path) : null; foreach ($array as $k => $v) { if ($filterKey === null || $filterKey === $k) { $sum += is_array($v) ? sumViaPath($v, $path) : $v; } } return $sum; } foreach ($filterSets as $path) { $results[json_encode($path)] = sumViaPath($teams, $path); } var_export($results);
Output for 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
array ( '[]' => 110, '[1]' => 70, '[2]' => 40, '[null,"AREA I"]' => 95, '[null,"AREA II"]' => 15, '[null,null,"blue"]' => 85, '[null,null,"green"]' => 25, '[null,"AREA I","blue"]' => 70, )

preferences:
95.65 ms | 402 KiB | 62 Q