Is there a function php
that returns the number of times an element is repeated within a array
?. If not, I'll have to iterate through each element and use a counter to see how many times it repeats.
Something like that, like the function count()
that has Python
. The output of that program would be 2, since the one is present twice in the array
.
with the function
array_count_values
The answer given to you how many the number and how many times it is repeated
I see two options, which would have no problem searching for values with commas or quotes.
The first option would be the one mentioned by @sioesi and @alvaro-montoro , being native it is probably very fast . In this case, you have to be careful because if the value doesn't exist, you can't find it:
But yes, if you are interested in comparing a single value, it is 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, produces another 10 elements long:With those amounts there should be no problem, but if you deal with long arrays it can consume a lot of memory, because you create one of similar size.
Instead, if you're trying to count a single value, it's easier to loop through the array and compare each value, using
foreach
. You can do it in a single line (2 instructions) if you are sure it$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:
Thus, it should be more efficient in memory management, since it only creates a numeric variable.
There is no function that returns exactly the number of times a particular value appears, but you could use the function
array_count_values
to count how many times all the data in the array appears.From there you could create your own function:
Although I imagine that, unless you need to count more than one element, it can be a bit excessive.
Try this:
Basically we pass the array to string and then substr_count() does the job for us, you'll see the output is "3" because the word "friend" appears three times in your array.
BEWARE that the
'amigo,'
equal element will add+1
to$count
, since it has a comma at the end, but you do not want to count it because it is a different element from the 'friend' element, which does not have a comma.Note that this could be memory inefficient if you process large amounts of data (you're copying all the data into a string).