-2

Close my question when it´sdifferent to this not duplicater, the case it´s different in all : PHP - count specific array values My question not the same

I have this array for example :

$array_test=array("gren","green","red","red","green","blue");

My idea is know inside loop number of elementos with the condition i want, the array for show it´s more complex and this is only example for understand i need, because try different ways with "count" and don´t show right this number in each case.

I try this :

foreach($array_test as $array_ts) {

if($array_ts=="green") { Count number of elements green /// }

if($array_ts=="red") { Count number of elements red /// }

if($array_ts=="blue") { Count number of elements blue /// }

}

Thank´s for the help, regards.

Jean
  • 13
  • 3

1 Answers1

-2

You can create an array and fill it with the count for each color:

$input = ["gren","green","red","red","green","blue"];

$count = [];

foreach ($input as $color) {
   if (array_key_exists($color, $count)) {
       $count[$color]++;
   } else {
       $count[$color] = 1;
   }
}

$count will contain:

["green"=>3, "red"=>2, "blue"=>1]
Elias Soares
  • 9,884
  • 4
  • 29
  • 59