0
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.

2
  • count() is a reserved function! And why you want to print 4?!? Commented Nov 8, 2014 at 14:56
  • @Rizier123: I guess because "Hi" is present 4 times in that array Commented Nov 8, 2014 at 15:08

1 Answer 1

3

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:

  • the function should return the $counter;
  • in the recursive call you should append the result: $counter += f();.

I have also applied two optional improvements:

  • you don't need to populate the variable $key as you don't need it
  • to compare two strings you can simply use == comparison operator (strcmp feels so old)

Live on codepad: http://codepad.org/ATiKV09d

Sign up to request clarification or add additional context in comments.

1 Comment

I guess $counter += count($value); should be $counter += myRecursiveCount($value);?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.