Forum Moderators: coopster

Message Too Old, No Replies

Create associateve array from array values?

         

endtheme

9:04 pm on Jul 15, 2008 (gmt 0)

10+ Year Member



Say I have an array such as this:

$array = array('red', 'red', 'red', 'green', 'blue');

I want to transform this into an associative array that lists the color value, and how many of each color values were in the array. So it would look like this.

Array
(
['red'] => 3
['blue'] => 1
['green'] => 1
)

How would I go about doing that?

Basically, I have a list of string values in an array. I want to output each string value (avoiding duplicates), and I want to output the amount of each value found within the array.

For example:

List
----
Red [3]
Blue [1]
Green [1]
Grey [5]
Black [2]

supermanjnk

9:43 pm on Jul 15, 2008 (gmt 0)

10+ Year Member



You could do something like this...

$array = array('red', 'red', 'red', 'green', 'blue');
$colors = array();
foreach ($array as $color) {
if (isset($colors[$color])) {
$colors[$color]++;
} else {
$colors[$color] = 1;
}
}
print_r($colors);

Little_G

9:53 pm on Jul 15, 2008 (gmt 0)

10+ Year Member



Hi,

I think array_count_values [php.net] does what you want.

Andrew

endtheme

10:19 pm on Jul 15, 2008 (gmt 0)

10+ Year Member



Thanks!