3v4l.org

run code in 300+ PHP versions simultaneously
<?php function freqCount(array $values, $searchValue): array { $frequencies = computeFrequencies($values, $searchValue, 0); return array_map( static function (int $depth) use ($frequencies) { return [$depth, $frequencies[$depth]]; }, array_keys($frequencies) ); } function computeFrequencies(array $values, $searchValue, int $depth): array { $frequencies = [$depth => 0]; foreach ($values as $value) { if ($value === $searchValue) { $frequencies[$depth]++; } elseif (is_array($value)) { foreach (computeFrequencies($value, $searchValue, $depth + 1) as $deeperDepth => $frequency) { $frequencies[$deeperDepth] = ($frequencies[$deeperDepth] ?? 0) + $frequency; } } } return $frequencies; } print_r(freqCount([1, 4, 4, [1, 1, [1, 2, 1, 1]]], 1)); print_r(freqCount([1, 5, 5, [5, [1, 2, 1, 1], 5, 5], 5, [5]], 5)); print_r(freqCount([1, [2], 1, [[2]], 1, [[[2]]], 1, [[[[2]]]]], 2));

preferences:
29.01 ms | 406 KiB | 5 Q