Click to See Complete Forum and Search --> : counting array elements


bsmbahamas
02-15-2007, 02:07 PM
is there an easy way to count how many times a particular element appears in an array?

Stephen Philbin
02-15-2007, 05:51 PM
Have a look at the documentation for array functions in PHP (http://www.php.net/manual/en/ref.array.php). It lists all the functions associated with arrays. You should find it very useful (along with the rest of the manual).

I think the particular function you are looking for is array_count_values() (http://www.php.net/manual/en/function.array-count-values.php). ;)

bsmbahamas
02-15-2007, 05:57 PM
I practically live at php.net, must of overlooked that array function,
i saw count, but couldn't figure it out.

thanks again.

:D

SlappyTheFish
02-16-2007, 10:39 AM
Count() will tell you how many elements you have in your array, but if you want to know how many times there is a particular element then just loop through the array.

For example, if you have an array of fruits and each element is the name of a fruit and you want to know how many times "banana" appears, then do this:

Array:

$fruits[] = 'orange';
$fruits[] = 'banana';
$fruits[] = 'apple';
$fruits[] = 'pear';
$fruits[] = 'banana';
$fruits[] = 'cherry';
$fruits[] = 'banana';

Code:


foreach ($fruits AS $fruit)
{
if ($fruit == 'banana')
{
$number_of_bananas++;
}
}

Will return $number_of_bananas = 3

bsmbahamas
02-16-2007, 10:48 AM
thanks for taking the time to really explain it,
i can definetely work with that to make it
dynamically count whichever elements are
being stored.

NightShift58
02-16-2007, 08:30 PM
First and foremost, read the documention on arrays, as suggested by Stephen Philbin. In it, you would have found the array_keys() (http://www.php.net/manual/en/function.array-keys.php) function, which will do exactly what you want to do in a single function call.

bsmbahamas
02-17-2007, 11:05 AM
First and foremost, read the documention on arrays, as suggested by Stephen Philbin. In it, you would have found the array_keys() (http://www.php.net/manual/en/function.array-keys.php) function, which will do exactly what you want to do in a single function call.

awesome. thanks for contributing.

this might solve another problem i ran into using array_unique().

thanks