php 检查数组PHP中特定值的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7960307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:42:15  来源:igfitidea点击:

Check how many times specific value in array PHP

phparrayscount

提问by DobotJr

I have an array named $uid. How can I check to see how many times the value "12" is in my $uid array?

我有一个名为 $uid 的数组。如何检查 $uid 数组中值“12”的次数?

回答by Niet the Dark Absol

Several ways.

几种方式。

$cnt = count(array_filter($uid,function($a) {return $a==12;}));

or

或者

$tmp = array_count_values($uid);
$cnt = $tmp[12];

or any number of other methods.

或任何数量的其他方法。

回答by Rafe Kettler

Use array_count_values(). For example,

使用array_count_values(). 例如,

$freqs = array_count_values($uid);
$freq_12 = $freqs['12'];

回答by MD. Shafayatul Haque

Very simple:

很简单:

$uid= array(12,23,12,4,2,5,56);
$indexes = array_keys($uid, 12); //array(0, 1)
echo count($indexes);

回答by Hammerite

Use the function array_count_values.

使用函数array_count_values

$uid_counts = array_count_values($uid);
$number_of_12s = $uid_counts[12];

回答by Eineki

there are different solution to this:

对此有不同的解决方案:

$count = count(array_filter($uid, function($x) { return $x==12;}));

or

或者

array_reduce($uid, function($c, $v) { return $v + ($c == 12?1:0);},0)

or just a for loop

或者只是一个 for 循环

for($i=0, $last=count($uid), $count=0; $i<$last;$i++)
    if ($uid[$i]==12) $count++;

or a foreach

或 foreach

$count=0;
foreach($uid as $current)
    if ($current==12) $count++;

回答by genesis

$repeated = array();
foreach($uid as $id){
    if (!isset($repeated[$id])) $repeated[$id] = -1;
    $repeated[$id]++;
}

which will result for example in

这将导致例如

array(
   12 => 2
   14 => 1
)