Dwza
Dwza

Reputation: 6565

Count specific array values with same part

I found a lot of samples how to count positions or occurrences in an arrays but actualy this doesnt solve my problem.

My Array looks like:

$foo = array(
          "foo"=>"bar",
          "bar"=>"foo",
          "hello"=>"world",
          "world"=>"hello",
          "grT1"=>"A",
          "grT2"=>"B",
          "grT3"=>"C",
          "grT4"=>"D",
          "grT5"=>"E",
          "gr1"=>2,
          "gr2"=>0,
          "gr3"=>,
          "gr4"=>5,
          "gr5"=>
)

What I want to achive is to count how many gr{i} are in my array.

The thing is, I dont want the count grT{i}. So the result for this sample should be 5.

array_count_values does not help me in this case.

My Try atm is:

$count = 0;
for($i=0;$i<count($foo);$i++){
    if(array_key_exists("gr".$i, $foo)){
        $count++
    }
}

is this the only way to do this ? or is there a nicer way ?

EDIT: Since I need the result for a loop (for) I would like to get rid of this loop.

Upvotes: 3

Views: 55

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Alternative solution using array_keys and array_filter functions:

$count = count(array_filter(array_keys($foo), function($v){
    return preg_match('/^gr\d+?/',$v);
}));
// $count is 5

Upvotes: 1

nospor
nospor

Reputation: 4220

array_reduce() will do the job

$count = array_reduce(array_keys($foo), function($c, $k){
  return preg_match('/^gr\d+$/', $k) ? ++$c : $c;
}, 0);

Upvotes: 1

Related Questions