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);
?>

Recommended Answers

All 5 Replies

preg_match_all('/\b(hello|world|bla|something|else)\b/', $str, $matches);
$count = count($matches[0]);

Or something like that.

$words = 'Hello world hello world this is hello world';
$words = explode(' ', $words);
$frequency = array();

foreach($words as $word) {
    $word = strtolower($word);

    if(isset($frequency[$word]))
        $frequency[$word] += 1;
    else
        $frequency[$word] = 1
}

echo '<pre>'; print_r($words); echo '</pre>';
<?php
$str = "    Hello world hello World this is      hello world    ";
$arr=str_word_count(strtoupper($str),1);
echo "<pre>";
foreach($arr as $value)
{
	$finalarr[$value]++;
}
echo print_r($finalarr);
echo "</pre>";
?>
$words = 'Hello world hello world this is hello world';
$words = explode(' ', $words);
$frequency = array();

foreach($words as $word) {
    $word = strtolower($word);

    if(isset($frequency[$word]))
        $frequency[$word] += 1;
    else
        $frequency[$word] = 1
}

echo '<pre>'; print_r($words); echo '</pre>';

ok but, in case when we have an entire text file containing thousands of words, what approach can we take ?

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.