function count($array){
$counter=0;
foreach($array as $key=>$value){
if(is_array($value)){
count($value);
}else{
if(strcmp($value, "Hi") == 0){
$counter++;
}
}
}
}
$arrays = array("Hi", "a", "Hi", "b", "c", array("c", "Hi", array("Hi"), "d"));
If I call count($arrays);
I want to print 4 in this case.
But my code keeps printing 0. It seems it does not return counter of "Hi" properly but I have no idea.
count()
is a built-in function of PHP, better if you change the name:
function myRecursiveCount($array, $needle = "Hi"){
$counter=0;
foreach($array as $value){
if(is_array($value)){
$counter += myRecursiveCount($value);
} else if ($value === $needle){
$counter++;
}
}
return $counter;
}
$inputs = array("Hi", "a", "Hi", "b", "c", array("c", "Hi", array("Hi"), "d"));
echo myRecursiveCount($inputs); // Prints 4
You need two edits:
$counter
;$counter += f();
.I have also applied two optional improvements:
$key
as you don't need it==
comparison operator (strcmp
feels so old)Live on codepad: http://codepad.org/ATiKV09d