I see two options, which would not be inconvenient when looking for values with commas or quotes.
The first option would be the one that mention @sioesi and @alvaro-montoro , to be native is probably very fast . In this case, you have to be careful because if the value does not exist, you can not find it:
<?php
function contar_valores($a,$buscado)
{
if(!is_array($a)) return NULL;
$v=array_count_values($a);
return array_key_exists($buscado,$a)?$v[$buscado]:0;
}
But yes, if you are interested in comparing a single value, you are creating an array in memory with one element for each unique value. For example, array(1,2,3,4,5,6,7,8,9,10,1)
, which is 11 long, generates another 10 long elements:
array(
[1]=>2,
[2]=>1,
[3]=>1,
[4]=>1,
[5]=>1,
[6]=>1,
[7]=>1,
[8]=>1,
[9]=>1,
[10]=>1,
)
With those amounts there should be no problem, but if you treat long arrays it can consume a lot of memory, because you create one of similar size.
On the other hand, if you try to count a single value, it is easier to go through the array and compare each value, using foreach
. You can do it in a single line (2 instructions) if you are sure that $a
is an array: $i=0;foreach($a as $v) if($buscado===$v) $i++;
If you want it as a function, you can do the following:
<?php
function contar_valores($a,$buscado)
{
if(!is_array($a)) return NULL;
$i=0;
foreach($a as $v)
if($buscado===$v)
$i++;
return $i;
}
Thus, it should be more efficient in memory management, since it only creates a numeric variable.