PHP COUNTIF: Custom Function Guide
There is no built-in countif function in PHP, but you can use a custom function to achieve a similar functionality. The countif function is commonly used to count the number of elements in an array or collection that meet a specific condition. Here is an example code:
function countif($array, $condition) {
$count = 0;
foreach($array as $element) {
if ($condition($element)) {
$count++;
}
}
return $count;
}
// 示例用法
$array = [1, 2, 3, 4, 5, 6];
$condition = function($num) {
return $num % 2 == 0;
};
echo countif($array, $condition); // 输出2,统计数组中偶数的个数
The countif function in the above example takes an array and a conditional function as parameters, then iterates through the array, applies the conditional function to each element, and increments a counter if the condition is met. It ultimately returns the number of elements that meet the condition. Similar functionality to countif can be achieved with custom functions.