tags:

views:

132

answers:

4

Is there a PHP function that lets you search an array recursively and return the number of instances a certain key 'x' occurs (regardless of how deep)?

A: 

Nope. Write your own! Recursion is fun! =D

Matchu
I agree about recursion. :p
Pikrass
A: 

This is pretty much what the array_count_values function is for, but if you're using a multi-dimensional array as you imply, if would be fairly trivial to put something together using the array_walk_recursive function.

middaparka
But this counts values not keys.
Felix Kling
@Felix - That's a tremendously valid point. My bad. :-)
middaparka
I mean in theory you could use it together with `array_keys` but as every key only occurs one time... ;-D
Felix Kling
+5  A: 

Now yes. :)

function count_key($array, $key) {
    $count = 0;
    foreach($array as $k => $val) {
        if($k == $key)
            $count++;
        if(is_array($val))
        $count += count_key($val, $key);
    }
    return $count;
}
Pikrass
Returns one too much
stef
A: 

This could help you.

function recursiveSum($array, $keyToSearch) {
    $total = 0;
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $total += recursiveSum($value, $keyToSearch);
        }
        else if($key == $keyToSearch) {
            $total += $value;
        }
    }
    return $total;
}

$total = recursiveSum($array, "test");
streetparade
Not totally correct, `else if` should be only `if`. Otherwise `$foo[$key] = array()` would not be taken into account.
Felix Kling
And why do you add the value of an element of the array to the counter?...
Felix Kling
@Felix yeah thats corect my bad :
streetparade
@Felix to return the summ of the array items like $a = array("test" =>1,array("test"=>2));$total = recursiveSum($array, "test");would return 3
streetparade
Yes but the OP asked for a function that **counts** the number of **occurrences** of a certain key, not the sum of the values of that key.
Felix Kling