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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…