19

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

0

6 Answers 6

33

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.

3
  • 1
    array_count_values() is not reliable if the count is zero because only found values become keys. Aug 23, 2019 at 12:56
  • @mickmackusa how is it not reliable? just do $tmp[9999] ?? 0 (if 9999 is not found) and it's good to go, I don't know why you would go and reply to everyone using it that it's not reliable just because of the key not existing.
    – C Alex
    May 15 at 14:45
  • My comments aim to inform readers who are unaware of fringe cases. Yes, null coalescing should be used. May 15 at 19:50
12

Use array_count_values(). For example,

$freqs = array_count_values($uid);
$freq_12 = $freqs['12'];
4
  • array_count_values won't work here. I don't do.. array_count_values($string) //or 12 as $string
    – DobotJr
    Oct 31, 2011 at 22:07
  • 2
    Current versions of PHP don't allow you to use [] notation after a funtion call.
    – Hammerite
    Oct 31, 2011 at 22:09
  • @Hammerite that's stupid, corrected Oct 31, 2011 at 22:10
  • array_count_values() is not reliable if the count is zero because only found values become keys. Aug 23, 2019 at 12:57
6

Very simple:

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

Use the function array_count_values.

$uid_counts = array_count_values($uid);
$number_of_12s = $uid_counts[12];
1
  • array_count_values() is not reliable if the count is zero because only found values become keys. Aug 23, 2019 at 12:58
2

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($i=0, $last=count($uid), $count=0; $i<$last;$i++)
    if ($uid[$i]==12) $count++;

or a foreach

$count=0;
foreach($uid as $current)
    if ($current==12) $count++;
0
$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
)

Not the answer you're looking for? Browse other questions tagged or ask your own question.