-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.

0

1 Answer 1

-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]
Sign up to request clarification or add additional context in comments.

4 Comments

$input is not an array though
No works, give me error
I missed typing the array brackets. Now it's right.
I missed typing the array brackets. Now it's right.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.