Php

Hey guys I am trying to solve this type of a problem in PHP

Hey guys I am trying to solve this type of a problem in PHP

`write a function count items that recursively passes through all arrays and cunts the number of occurrences of a given item. keep in mind that array can be nested within each other

For example, ArraySearch::countItem($arr, 'apple') for the array below should return 2.
 
$arr = [
"apple",
["banana", "strawberry", "apple"]
];

 
This is what I got so far
 
<?php
class ArraySearch
{
public static function countItems($arr, $item)
{
return NULL;
}
}

$arr = [
"apple",
["banana", "strawberry", "apple"]
];
echo ArraySearch::countItems($arr, "apple");
You already invited:

Paul Williamson

Upvotes from: Tom

<?php

class ArraySearch {

public function __construct(array $array, string $item)
{
$this->array = $array;
$this->item = $item;
$this->count = 0;
}

public function findItems()
{
array_walk_recursive($this->array, 'ArraySearch::countItems');
echo "{$this->item} was found {$this->count} times.".PHP_EOL;
}

public function countItems(&$value)
{
if ($value === $this->item) {
$this->count++;
}
}
}

$arr = [
"apple",
["banana", "strawberry", "apple"]
];

$obj = new ArraySearch($arr, "apple");
$obj->findItems();
Result: `apple was found 2 times.`

If you wanna answer this question please Login or Register