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


bsmbahamas
02-22-2007, 03:07 PM
is there a built in function here http://bs.php.net/manual/en/ref.array.php
that will allow me to count how many times a particular element occurs in an array?

i've created a unique array and i want to loop through each element of
the unique array and have it count how many times that particular element
occurs in the original array.

i tried

for( $i = 0; $i < sizeof($unique_array); $i++ ){
$temp_count = count($original_array,$unique_array[$i]);
echo "<li>$unique_array[$i]: $temp_count";
}

am i using count() incorrectly or does it not work this way?

the original array will change over time, so i first create a unique array,
and then loop throught the unique array one element at a time and count
how many times that particular element occured in the original array
and display it in a table. so if there are 12 different elements, but they
are repeated many times, it should produce a neat table with how many times
each of the 12 elements occurs.


array_count_values() works fine, but i don't know how to access the elements in the array it creates so i can have it print out in a table instead
of accross my webpage like print_r($my_array); does.

help please

NightShift58
02-22-2007, 03:43 PM
<?php
$arrTEST = array("a", "a", "a", "b", "b", "c");

$arrCOUNT = array_count_values($arrTEST);

FOREACH ($arrCOUNT as $key => $count) :
echo "Value " . $key . " occurs " . $count . " time(s)<br>";
ENDFOREACH;
?>

MatMel
02-22-2007, 03:45 PM
Count is an alias of sizeof and takes only 1 argument.

If I've understood your script you want to know how many values are there...
You could use asort() (http://bs.php.net/manual/en/function.asort.php) to sort the values and then always look if the next value is the same as the actual one ...


edit: okaaay .... ;)

NightShift58
02-22-2007, 03:47 PM
Using asort() and a loop to count is unnecessary, as array_count_values() will do the job.

bsmbahamas
02-23-2007, 07:13 AM
i didn't realize that count() was an alias of sizeof(), that explains why it was not working.

i kinda figured that i could assign the results of array_count_values();
to a variable like nightshift did but was unable to access the elements
after i did that.

i think the code nightshift supplied will do the job just fine.

thanks guys.