Group and add array with PHP

Asked

Viewed 4,531 times

11

I need to know how to group and add one array, but I’m not finding out how to do.

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

wanted a comeback like this

3
1
2

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

2 answers

17


Example of array_count_values()

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

or your:

 $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  
)   
'''  

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

  • 1

    That’s exactly what Flavio, thank you!

4

Alternative to the above 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 that case, it gives the same result:

array(3) {
  'vermelho' =>
  int(3)
  'verde' =>
  int(1)
  'azul' =>
  int(2)
}
  • I do not think that would be an alternative, since the function reported in the previous question solves the problem. There is no need to "recreate" what is already created. -1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.