1

Hey! I am trying to count the number of times a certain string exists inside an array. I have tried this.. My array:

$test = array('correct','correct','incorrect','incorrect','correct');

in_array('correct',$test); // only gives me true

I thought about count(); but that only returns the count of items...So how can count for how many "correct" strings are in that array?

Thanks!

5 Answers 5

4

How about using preg_grep ?

$count = count(preg_grep('/^correct$/', $test));
Sign up to request clarification or add additional context in comments.

Comments

1

How about:

$count = 0;
foreach($test as $t)
    if ( strcmp($t, "correct") == 0)
         $count++;

3 Comments

It's the first time I see someone using strcmp to compare two string in PHP! (BTW, I think that here, == runs way faster)
Force of habit I guess. Of interest: stackoverflow.com/questions/3333353/…
Sure, it might be useful, but it's not so often that you need to find the greatest of two string (I never had to)! ^^ About speed: snipplr.com/view/758/speed-test-strcmp-vs-
1

I'd combine count and array_filter for this:

$count = count(array_filter($test, function($val) {
    return $val === 'correct';
}));

Note that the function syntax supports PHP >=5.3 only.

Comments

0
$count = 0;

foreach ($test as $testvalue) {
if ($testvalue == "correct") { $count++; }
}

Comments

0
function count_instances($haystack, $needle){
  $count = 0;
  foreach($haystack as $i)
    if($needle == $i)
      $count++;
  return $count;
}

Comments

Your Answer

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