I have a txt file and format is like this
First line: qinetiq, sarah, sarah, qinetiq, stacey, qinetiq, sarah, stacey
Second line: stacey, qinetiq, sarah, stacey, stacey, qinetiq, sarah, qinetiq
I am trying to count the number of times, it has "sarah", "stacey" and "qinetiq"
The code finds the first word qinetiq on first line and for everything else it returns Null and 0. I am new to php and I can't see where i am making mistake.

foreach ($str as $s) {
$words= explode(",", $s ); 
for($i =0; $i < count($words); $i++) { 

//echo $words[$i]."<br>"; //this line works 
                        // and prints all entries from the file

if ($words[$i] == "qinetiq")
{
$qincount += 1;
}
if ($words[$i] == "sarah")
{
$saracount += 1;

}
else 
{
$staccount += 1;
}
}
echo"<br>";

echo "<br>";
echo "count for qinetiq: ";
print $qincount;
echo "sarah count: ";
print $saracount;
echo "ALL OTHER ";
print $staccount;

}

The result just displays count for qinetiq as 1 and all other counts are 0. :(
I tried to solve it by doing somthing like this

if( in_array("qinetiq", $words) ){
    $qincount += 1;
}

This doesn't work either then i thought of doing forreach loop within a forreach loop....
But now i have no clue. It seems like the if function picks up value first time but after that $words[$i] it returns null...
I am stuck on this for 2 days now..help plz!

Does this help?

$text = 'qinetiq, sarah, sarah, qinetiq, stacey, qinetiq, sarah, stacey
stacey, qinetiq, sarah, stacey, stacey, qinetiq, sarah, qinetiq';

$num_qinetiq = substr_count($text, 'qinetiq');
$num_sarah = substr_count($text, 'sarah');
$num_stacey = substr_count($text, 'stacey');

echo "Count for qinetiq: $num_qinetiq <br />";
echo "Count for Sarah: $num_sarah <br />";
echo "Count for Stacey: $num_stacey";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.