5

I want an easy way to count a number of times the string "Apple" has present in the given

# My Array  :

$arr = array(
             1 => "Apple",
             2 => "Orange",
             3 => array(1=>"Bananna",2=>"Apple"),
             4 => "Grape",
             5 => "Apple",
             6 => array(1=>"Grape"),
             7 => "Orange");

# Want to count only "Apple"

$needle         = "Apple";

# My Function :

 function arrsearch($needle,$haystack,$return) {
    if(!is_array($haystack)) {
      return false;
    } 
    foreach($haystack as $key=>$val) {
        if(is_array($val)) {
              $return     = arrsearch($needle,$val,$return);
        }else if(strtolower($val) == strtolower($needle)) {
          $return[] = $key;
        }
    }
    return $return;
 }

 $var = arrsearch("Apple",$arr,array());
 echo " Output : ".count($var);

 # Output : 3

I used the above function to find the number of times the string "Apple" in the array. Suggest me the best one.

3 Answers 3

8

You could use array_walk_recursive:

function search_for($arr, $term)
{
    $count = 0;

    array_walk_recursive($arr, function($item, $idx, $term) use (&$count) {
      if (false !== stripos($item, $term)) {
          ++$count;
      }
    }, $term);

    return $count;
}

search_for($arr, 'Apple'); // returns 3

The expression function($item, $idx, $term) use (&$count) { .. } is an anonymous function declaration; it works just like a regular function, but you can inherit variables from the parent scope by using use ($var) or use (&$var) if you need to modify it too. More examples can be found on the manual page.

Update

For versions of PHP < 5.3, you'd have to encapsulate the counter using objects:

class RecursiveArraySearcher
{
    private $c = 0;

    public static function find($arr, $term)
    {
        $obj = new self;

        array_walk_recursive($arr, array($obj, 'ismatch'), $term);

        return $obj->c;
    }

    public function ismatch($item, $key, $term)
    {
        if (false !== stripos($item, $term)) {
            ++$this->c;
        }
    }
}

echo RecursiveArraySearcher::find($arr, 'Apple'); // 3
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, can you post a link explaining the use expression?
@JanTuroň Of course, I've updated my answer to explain the use of anonymous functions.
2

You can use a recursive function like this ..

function finditem($item,$array){
    $count = 0;
    foreach($array as $key => $value){
        if(is_array($value) == true){
            $countx = finditem($item,$value);
            $count = $count + $countx;
        }else if($value == $item)
            $count++;
    }
    return $count;
}

echo finditem("Apple",$arr);

Hope it helps.

Comments

2

Another solution is to flat the array and count the values:

<?php

function search_for($arr, $term) {
  $flatten_array = array();
  $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
  foreach($it as $v) {
    $flatten_array[] = $v;
  }

  $count_values = array_count_values($flatten_array);
  return $count_values[$term];
}

echo search_for($arr, 'Apple'); // print 3

Comments

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.