I want to find frequency of all words in a given string. I wrote this code, but it is not giving correct output. Plz help
<?php
//string here
$wordsArray = "Hello world hello world this is hello world";
//echo($wordsArray);
//function here
$startPosForWord;
$endPosForWord;
$wordToMatch;
$word;
$scannedWords;
$occurance = 0;
$i;
$j;
for($i = 0 ; $i < strlen($wordsArray); $i++)
{
//here we will search string for single single word
if($wordsArray[$i] != ' ')
{
$wordToMatch = $wordToMatch . $wordsArray[$i];
}
//once a word is found which is delimited by a space, we will send it to find it's frequency
else
{
$wordToMatch = strtolower($wordToMatch);
//insert into scanned words array
// echo nl2br($scannedWords." ".$wordToMatch."\n");
if (strstr($scannedWords,$wordToMatch) == "") //this means that currently scanned word is not in our list of scanned words
{
$scannedWords = $scannedWords.$wordToMatch." ";
for($j = 0 ; $j < strlen($wordsArray); $j++)
{
if($wordsArray[$j] != ' ')
{
$word = $word . $wordsArray[$j];
}
else
{
$word = strtolower($word);
if($wordToMatch == $word)
$occurance ++ ;
$word = "";
}
}
echo nl2br("The word: ".$wordToMatch . " Occurs: ". $occurance." times and the i position is:". $i."\n");
//clean up
$wordToMatch = "";
$occurance = 0;
}
else
{
$wordToMatch = "";
}
}
}
echo("scanned words are: " . $scannedWords);
?>