I have an array named $uid. How can I check to see how many times the value "12" is in my $uid array?
6 Answers
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.
-
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 AlexMay 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
4
-
array_count_values won't work here. I don't do.. array_count_values($string) //or 12 as $string– DobotJrOct 31, 2011 at 22:07
-
2Current versions of PHP don't allow you to use
[]
notation after a funtion call. Oct 31, 2011 at 22:09 -
-
array_count_values()
is not reliable if the count is zero because only found values become keys. Aug 23, 2019 at 12:57
Very simple:
$uid= array(12,23,12,4,2,5,56);
$indexes = array_keys($uid, 12); //array(0, 1)
echo count($indexes);
Use the function array_count_values.
$uid_counts = array_count_values($uid);
$number_of_12s = $uid_counts[12];
-
array_count_values()
is not reliable if the count is zero because only found values become keys. Aug 23, 2019 at 12:58
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++;
$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
)