What are the best practices for efficiently counting occurrences of a specific key in a multidimensional array in PHP?

When counting occurrences of a specific key in a multidimensional array in PHP, one efficient approach is to use a recursive function that iterates through the array and checks each element for the specified key. By using recursion, you can handle arrays of any depth. Additionally, you can keep track of the count using a variable that is passed by reference to the recursive function.

function countKeyOccurrences($array, $key, &$count) {
    foreach ($array as $value) {
        if (is_array($value)) {
            countKeyOccurrences($value, $key, $count);
        } else {
            if ($value === $key) {
                $count++;
            }
        }
    }
}

$array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

$count = 0;
countKeyOccurrences($array, 5, $count);

echo "Occurrences of key 5: " . $count;