Issue
The contents of this question have been removed due to a DMCA Takedown request by TestDome d.o.o.
Solution
This happens because your array $arr
contains a string (apple
) and arrays:
$arr = [
"apple",
["banana", "strawberry", "apple"],
["banana", "strawberry", "apple", ["banana", "strawberry", "apple"]]
];
$count = 0;
foreach ($arr as $arritem) {
// first iteration: $arritem is "apple"
// second iteration: $arritem is ["banana", ...]
// third iteration: $arritem is ["banana", ...]
if ($arritem === "apple") {
$count++;
}
}
echo $count;
$arritem === "apple"
only holds true for one element in the array, hence the output 1
.
How to fix ? Use array_walk_recursive
to recursively walk the array(s):
$count = 0;
array_walk_recursive($arr, function($item) use (&$count) {
if ($item === "apple") ++$count;
});
echo $count; // outputs 4
Answered By - marco-a
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.