How to use str_word_count() and array_count_values() Functions In PHP
The str_word_count()
function can be used to break down a string into an array of words. Combining this with array_count_values()
allows us to count the occurrences of each word.
PHP
<?php $file = file_get_contents ( 'gfg.txt' ); $words = str_word_count ( $file , 1); $wordCounts = array_count_values ( $words ); foreach ( $wordCounts as $word => $count ) { echo "$word: $count\n" ; } ?> |
Output:
Welcome: 3 to: 2 w3wiki: 2 Hello: 1
How to Count Occurrences of Each Word in Given Text File in PHP ?
PHP is a server-side scripting language used for web development and offers powerful functionalities for text processing. Given a text file and want to count the occurrences of each word in it. PHP provides several approaches to achieve this.
Filename: gfg.txt
Welcome to w3wiki
Welcome to w3wiki
Hello Welcome