Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of times a string in mixed array php

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.

like image 609
Selva Avatar asked Dec 15 '12 09:12

Selva


1 Answers

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
like image 81
Ja͢ck Avatar answered Oct 03 '22 06:10

Ja͢ck