To count the number of occurrences of a specified element in an array in PHP, you can use functions like array_count_values
or loops to iterate through the array and count each occurrence.
In this example,
$numbers
with values 10, 20, 30, 40, 30, 50.array_count_values
function to count the occurrences of element 30 in the array.array_count_values
function returns an associative array where the keys are the array values and the values are their respective counts.<?php
$numbers = [10, 20, 30, 40, 30, 50];
$countArray = array_count_values($numbers);
$count = $countArray[30];
echo "Number of occurrences of element 30: $count";
?>
Number of occurrences of element 30: 2
In this example,
$fruits
with values 'apple', 'banana', 'cherry', 'banana'.<?php
$fruits = ['apple', 'banana', 'cherry', 'banana'];
$count = 0;
foreach ($fruits as $fruit) {
if ($fruit === 'banana') {
$count++;
}
}
echo "Number of occurrences of element 'banana': $count";
?>
Number of occurrences of element 'banana': 2
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in PHP language with well detailed examples.