user2706762
user2706762

Reputation: 397

Aggregate and count an array

I have an array and i want to aggregate each word in it and count them, like so:

 Array
    (
        [0] => Notice
        [1] => co
        [2] => co
        [3] => Notice
        [4] => co
        [5] => co
        [6] => sls
    ) 

should look like this:

Array
(
    [Notice] => 2
    [co] => 4
    [sls] => 1
)

what is a ggod way to do that?

thanks

Upvotes: 2

Views: 127

Answers (2)

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16086

Try like this:

<?php
$array = array("Notice", "co", "co", "Notice", "co", "co", "sls");
print_r(array_count_values($array));
?>

Output

Array
(
    [Notice] => 2
    [co] => 4
    [sls] => 1
)

For more info: http://www.php.net/manual/en/function.array-count-values.php

Upvotes: 2

You need to look at array_count_values()

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

OUTPUT :

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

Upvotes: 4

Related Questions