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)?
4 Answers
I would use array_walk_recursive()
. Example:
$a = array(1,2,3,'x',array(4,5,'x',array(6,7,8,'x')));
$v = "x";
$i = 0;
array_walk_recursive($a, function($val, $key) use (&$i, $v) {
if ($val == $v) {
$i++;
}
});
echo $i;
Output:
3
You can traverse the array recursively (that is regardless of the depth) and then count the values:
$array = array(1, 2, 3, 'x', array(4, 5, 'x', array(6, 7, 8, 'x')));
$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$xCount = 0;
foreach ($rit as $value) {
if ($value === 'x') {
$xCount++;
}
}
var_dump($xCount); # int(3)
A variation of this is to convert this iteration into an array again and count values:
$array = array(1, 2, 3, 'x', array(4, 5, 'x', array(6, 7, 8, 'x')));
$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$allCount = array_count_values(iterator_to_array($rit, FALSE));
print_r($allCount);
Output/Result:
Array
(
[1] => 1
[2] => 1
[3] => 1
[x] => 3
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
)
See as well:
You could write a simple recursive function that does what you want. I didn't test this, but the idea would be something like:
$count = 0;
function findKey($array,&$count){
if(!empty($array)){
foreach($array as $key => $childArray){
if($key == 'keyImLookingFor'){
$count++;
}
findKey($childArray,$count);
}
}
}
$count should then contain your number of key occurrences. Again, this might need some cleanup.
$array = array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => array('key1' => 'val3'));
$count = 0;
function key_count($val, $key){
global $count;
if($key == "key1"){
$count++;
}
}
array_walk_recursive($array, 'key_count');
echo $count;