What are some best practices for iterating through an array and counting occurrences of a specific value in PHP?

When iterating through an array in PHP and counting occurrences of a specific value, it is best to use a foreach loop to go through each element of the array and compare it with the specific value. If the element matches the specific value, increment a counter variable. Finally, return the count of occurrences.

// Sample array
$array = [2, 3, 4, 2, 5, 2, 6];
$specificValue = 2;

// Counter variable to store occurrences
$count = 0;

// Iterate through the array and count occurrences of specific value
foreach ($array as $element) {
    if ($element == $specificValue) {
        $count++;
    }
}

// Output the count of occurrences
echo "The specific value $specificValue occurs $count times in the array.";