What are best practices for structuring PHP functions to count values in arrays?

When counting values in arrays in PHP, it is best practice to create a reusable function that takes in the array and the value to count, and returns the count of that value. This allows for cleaner and more maintainable code.

function countValueInArray($array, $value) {
    $count = 0;
    foreach ($array as $item) {
        if ($item == $value) {
            $count++;
        }
    }
    return $count;
}

// Example of how to use the function
$array = [1, 2, 3, 4, 2, 2];
$value = 2;
echo countValueInArray($array, $value); // Output: 3