An easy way to do this is to read the complete file in as a string with file_get_contents()
, split it up on whitespace, and run the resulting array through array_count_values()
$file = file_get_contents( 'text_file.txt');
$array = preg_split( '/\s+/', $file);
$counts = array_count_values( $array);
Done!
However, this isn’t perfect, as punctuation can mess up your count. So, as Mark Baker points out, we can go back to my original method of getting all of the words in the file with str_word_count()
, then running that array through array_count_values()
:
$file = file_get_contents( 'text_file.txt');
$words = str_word_count( $file, 1);
$counts = array_count_values( $words);
2
solved Interview – how calculate the frequency of each word in a text file