Skip to content

Instantly share code, notes, and snippets.

@dasider41
Created September 3, 2019 23:39
Show Gist options
  • Save dasider41/a86be56f01cfe0f4f5a73e0811f0fda3 to your computer and use it in GitHub Desktop.
Save dasider41/a86be56f01cfe0f4f5a73e0811f0fda3 to your computer and use it in GitHub Desktop.
<?php
function arrayFlat(array $array): array
{
return array_reduce($array, function ($acc, $item) {
return array_merge($acc, is_array($item) ? arrayFlat($item) : [$item]);
}, []);
}
function countItems(array $arr, string $item): int
{
return array_count_values(arrayFlat($arr))[$item];
}
$arr = [
"apple",
[
"banana", "strawberry", "apple",
[
"banana", "strawberry", "apple",
[
"banana", "strawberry", "apple"
]
]
]
];
var_dump(countItems($arr, "apple") === 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment