user381800
user381800

Reputation:

How to count the number of certain string inside array?

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!

Upvotes: 1

Views: 623

Answers (5)

Dan Soap
Dan Soap

Reputation: 10248

How about using preg_grep ?

$count = count(preg_grep('/^correct$/', $test));

Upvotes: 4

Thomas Hupkens
Thomas Hupkens

Reputation: 1590

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

Upvotes: 0

Adam Moss
Adam Moss

Reputation: 5712

$count = 0;

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

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237827

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.

Upvotes: 1

Ryan
Ryan

Reputation: 28177

How about:

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

Upvotes: 1

Related Questions