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 Answers5

4

How about using preg_grep ?

$count = count(preg_grep('/^correct$/', $test));
Dan Soap
  • 10,114
  • 1
  • 40
  • 49
1

How about:

$count = 0;
foreach($test as $t)
    if ( strcmp($t, "correct") == 0)
         $count++;
Ryan
  • 26,884
  • 9
  • 56
  • 83
  • It's the first time I see someone using `strcmp` to compare two string in PHP! (BTW, I think that here, == runs way faster) – Thomas Hupkens May 18 '11 at 21:58
  • Force of habit I guess. Of interest: http://stackoverflow.com/questions/3333353/php-string-comparison-vs-strcmp – Ryan May 18 '11 at 22:04
  • 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: http://snipplr.com/view/758/speed-test-strcmp-vs-/ – Thomas Hupkens May 18 '11 at 22:11
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.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0
$count = 0;

foreach ($test as $testvalue) {
if ($testvalue == "correct") { $count++; }
}
Adam Moss
  • 5,582
  • 13
  • 46
  • 64
0
function count_instances($haystack, $needle){
  $count = 0;
  foreach($haystack as $i)
    if($needle == $i)
      $count++;
  return $count;
}
Thomas Hupkens
  • 1,570
  • 10
  • 16