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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With