Reputation:
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
Reputation: 10248
How about using preg_grep
?
$count = count(preg_grep('/^correct$/', $test));
Upvotes: 4
Reputation: 1590
function count_instances($haystack, $needle){
$count = 0;
foreach($haystack as $i)
if($needle == $i)
$count++;
return $count;
}
Upvotes: 0
Reputation: 5712
$count = 0;
foreach ($test as $testvalue) {
if ($testvalue == "correct") { $count++; }
}
Upvotes: 0
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
Reputation: 28177
How about:
$count = 0;
foreach($test as $t)
if ( strcmp($t, "correct") == 0)
$count++;
Upvotes: 1