What function can be used to count the occurrence of a specific word in a text file in PHP?

To count the occurrence of a specific word in a text file in PHP, you can read the contents of the file, split the text into an array of words, and then use the array_count_values() function to count the occurrences of each word. Finally, you can access the count of the specific word you are interested in.

$file = 'example.txt';
$wordToCount = 'specific_word';

$content = file_get_contents($file);
$words = str_word_count($content, 1);
$wordCounts = array_count_values($words);

if(isset($wordCounts[$wordToCount])){
    $count = $wordCounts[$wordToCount];
    echo "The word '$wordToCount' occurs $count times in the file.";
} else {
    echo "The word '$wordToCount' does not occur in the file.";
}