(PHP)检查数组中的项
我有这样一个数组: 数组(a,b,c,a,b) 现在,如果我想检查在数组中可以找到多少个“b”实例,我将如何继续。这将返回一个关联数组,其中(PHP)检查数组中的项,php,arrays,Php,Arrays,我有这样一个数组: 数组(a,b,c,a,b) 现在,如果我想检查在数组中可以找到多少个“b”实例,我将如何继续。这将返回一个关联数组,其中$arr中的每个值作为键,该值在$arr中的频率作为值。例如: $arr = array(1, 2, 3, 4, 2); $counts = array_count_values($arr); $count_of_2 = $counts[2]; 有关详细信息,请参阅文档。这似乎就是你要找的 $array = array('a', 'b', 'c', 'a'
$arr
中的每个值作为键,该值在$arr
中的频率作为值。例如:
$arr = array(1, 2, 3, 4, 2);
$counts = array_count_values($arr);
$count_of_2 = $counts[2];
有关详细信息,请参阅文档。这似乎就是你要找的
$array = array('a', 'b', 'c', 'a', 'b');
$counts = array_count_values($array);
printf("Number of 'b's: %d\n", $counts['b']);
var_dump($counts);
输出:
‘b’的数目:2
数组(3){[“a”]=>int(2)
[“b”]=>int(2)
[“c”]=>int(1) }
尽管有一些奇特的方法,程序员应该能够使用非常基本的编程运算符来解决这个问题
知道如何使用循环和条件是绝对必要的
$count = 0;
$letters= array("a","b","c","a","b");
foreach ($letters as $char){
if ($char == "b") $count = $count+1;
}
echo $count.' "b" found';
不是火箭科学。您可以使用此函数计算实例数
$b = array(a,b,c,a,b);
function count_repeat($subj, $array) {
for($i=0;$i<count($array);$i++) {
if($array[$i] == $subj) {
$same[] = $array[$i]; //what this line does is put the same characters in the $same[] array.
}
return count($same);
}
echo count_repeat('b', $b); // will return the value 2
$b=数组(a、b、c、a、b);
函数计数\u重复($subc,$array){
对于($i=0;$i)