Robbert
Robbert

Reputation: 31

Count specific field in array

I have an array (paint) where the output looks like this:

array(3) {
   ["id"]=> string(1) "2"
   ["type"]=> string(1) "O"
   ["number"]=> string(1) "1"
}

array(3) {
   ["id"]=> string(1) "3"
   ["type"]=> string(1) "W"
   ["number"]=> string(1) "3"
}
array(3) {
   ["id"]=> string(1) "4"
   ["type"]=> string(1) "W"
   ["number"]=> string(1) "5"
}

Etc.

What I am trying is how often the type field contains W. So in this case I should have an output of 2. He should skip the first because there the type field is O.

What I tried:

 $sum = count($paint["type=W"]);

That doesn't work though. Is it possible to just count how often the type value is W?

Upvotes: 0

Views: 223

Answers (4)

North-Wind
North-Wind

Reputation: 156

Using a while loop:

<?php
$paint = array();
$i=0;
$x=0;
while($i<count($paint)){
    if($paint[$i][1]=="W"){
        $x++;
    }
    $i++;
}

echo "result: $x"; --> 2

Upvotes: 0

Sahil Gulati
Sahil Gulati

Reputation: 15141

Hope this simple one will be helpful. Here we are using array_column on array to get all the values having key as type and then counting values using array_count_values.

Try this code snippet here

$result=array_count_values(array_column($array,"type"));
print_r($result["W"]);

Output: 2

Upvotes: 1

finder2
finder2

Reputation: 1084

What about a simple for loop?

 var count = 0;
 for (var i =0; i< array.length; i++) {
      if($paint[i]['type'] === 'W'){
           count++;
      }
 }

Upvotes: 0

t1gor
t1gor

Reputation: 1292

Try using array_filter:

$typeW = array_filter($array1, fucntion($sub) {
    return $sub['type'] === 'W';
});
echo count($typeW);

Upvotes: 1

Related Questions