PHP 如何计算数组中的 "subINT"
PHP How to count "subINT" in an array
比如我有一个数组[1, 2, 1, 3, 4, 5]
我需要计算这个数组中的 subINT。
substr_count();
不起作用,因为数组中的值不是字符串
我需要应该 return subint_count($array, 1)
=> 2
的 subint 函数
或者例如数组 [1, 1, 1, 4, 5, 6]
应该 return subint_count($array, 1)
=> 3
这应该有效:
function subint_count($array, $n) {
$occurences = 0;
foreach ($array as $item) {
if ($item == $n) $occurences++;
}
return $occurences;
}
subint([1,2,3,1,1], 1); // returns 3
function sub_int($array, $n) {
$count = 0; //initialize count
foreach($array as $val){ //loop through array
if($val === $n) { //check if array element === num Strict comparison. Use == if you don't want strict.
$count++; //increment count
}
}
return $count;
}
print_r(sub_int([1,1,3,4,1])); // should print 3
比如我有一个数组[1, 2, 1, 3, 4, 5]
我需要计算这个数组中的 subINT。
substr_count();
不起作用,因为数组中的值不是字符串
我需要应该 return subint_count($array, 1)
=> 2
或者例如数组 [1, 1, 1, 4, 5, 6]
应该 return subint_count($array, 1)
=> 3
这应该有效:
function subint_count($array, $n) {
$occurences = 0;
foreach ($array as $item) {
if ($item == $n) $occurences++;
}
return $occurences;
}
subint([1,2,3,1,1], 1); // returns 3
function sub_int($array, $n) {
$count = 0; //initialize count
foreach($array as $val){ //loop through array
if($val === $n) { //check if array element === num Strict comparison. Use == if you don't want strict.
$count++; //increment count
}
}
return $count;
}
print_r(sub_int([1,1,3,4,1])); // should print 3