-1

I am trying to count how many times Apple appears in this array

$fruits = array (
"Apple",
 array("Apple", "Kiwi", "Tomato")
 );

Is this a multidimension array? How would I be able to check the total count apple appears?

LaraC
  • 19
  • 3
  • Do you want to make it extremely robust regardless of how deep the array is(without flattening) ? – nice_dev Dec 15 '20 at 05:58
  • @Robin - Yes thank you. This lead me to the solution, I first flattened the array then used the count and array filter methods to return me the total times Apple appeared in the new array. – LaraC Dec 15 '20 at 05:59
  • There is no need of flattening to be honest. It is just extra memory consumption! – nice_dev Dec 15 '20 at 06:06

1 Answers1

0

First you need to flat the array.

$fruits = array (
"Apple",
 array("Apple", "Kiwi", "Tomato")
 );
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($fruits));
foreach($it as $v) {
  $flat_arr[] = $v;
}

Then filter items that only have 'Apple':

$result_count = count(array_filter($flat_arr, function($item) {
    return substr('Apple', $item) !== false;
}));
SEYED BABAK ASHRAFI
  • 4,093
  • 4
  • 22
  • 32