Grouping and adding array with PHP

10

I need to know how to group and add array , but I'm not sure how to do it.

$array = array("vermelho", "vermelho", "vermelho", "verde", "azul", "azul");

I wanted a return like this

3
1
2

That is, it will group and add up the amount of equal items.

    
asked by anonymous 08.01.2014 / 00:06

2 answers

17

Example of array_count_values()

<?php
$array = array(1, "ola", 1, "mundo", "ola");  
$a = array_count_values($array);  
?>  

or yours:

 $array = array("vermelho", "vermelho", "vermelho", "verde", "azul", "azul");
 $a = array_count_values($array); 
 var_dump($a);

The above example will print:

Array   
(  
    [1] => 2  
    [ola] => 2   
    [mundo] => 1  
)   
'''  

link

    
08.01.2014 / 00:36
4

Alternative to the already mentioned array_count_values() :

$array = array("vermelho", "vermelho", "vermelho", "verde", "azul", "azul");

foreach ($array as $item) {
    if(!isset($count[$item])) $count[$item] = 0;
    $count[$item]++;
}

var_dump($count);

In this case, it gives the same result:

array(3) {
  'vermelho' =>
  int(3)
  'verde' =>
  int(1)
  'azul' =>
  int(2)
}
    
08.01.2014 / 00:46