3

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.

1
  • Maybe clean up the loop with foreach loop. while is unnecessary here Commented Jun 9, 2016 at 14:15

2 Answers 2

1

array_reduce() will do the job

$count = array_reduce(array_keys($foo), function($c, $k){
  return preg_match('/^gr\d+$/', $k) ? ++$c : $c;
}, 0);
Sign up to request clarification or add additional context in comments.

10 Comments

But my answer is more optimised because I am not returning array only right number and do not have count after that elements of that array. I am telling it only as a explain not complain ;)
Accepted your answere because in 10k requests its 0.02 sec. faster :)
of course I do. In my case I need all performance I can get :)
Did you check your solution with loop? How fast was that?
on 100.000 its 0.24 for loop, yours is 0.31 and the other ones is 0.35
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.