How do I count the frequency of each array value?
posted by best71 on 2009-07-07 12:27:34
Hello,
This is my arrayI count the values of the array with:can I optimize it?
Thanks
This is my array
$a = array(); $a[0] = "fruit"; $a[1] = "apple"; $a[2] = "tree"; $a[3] = "limon"; $a[4] = "apple"; $a[5] = "limon"; ...
$new_array = array(); for($i=0;$i<count($a);$i++){ if (array_key_exists($a[$i], $new_array)) $new_array[$a[$i]] = $new_array[$a[$i]]+1; else $new_array[$a[$i]] = 1; } print_r($new_array);
Thanks

12
Sure, there is PHP function to count all the values of an array, take a look at array_count_values()
Example:
Example:
$a = array(); $a[0] = "fruit"; $a[1] = "apple"; $a[2] = "tree"; $a[3] = "limon"; $a[4] = "apple"; $a[5] = "limon"; print_r(array_count_values($a));
Answer the question
Top Users
- dail (12)
- livin52 (3)
- camu (3)
- softweb (2)
- Nadine (1)
- Josware (1)
- lfelipecr (1)
- gregoriohc (1)
- Mitu (1)
- ryan714 (1)