Create a PHP script that counts the number of occurrences of each word in a given sentence.

function countWordOccurrences($sentence) {
    $words = str_word_count(strtolower($sentence), 1);
    $wordCount = array_count_values($words);
    return $wordCount;

$inputSentence = "The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs away.";
$wordOccurrences = countWordOccurrences($inputSentence);

echo "<pre>";
echo "</pre>";


  • The script defines a function countWordOccurrences that takes a sentence as input and counts the occurrences of each word.
  • It uses str_word_count to extract an array of lowercase words from the sentence.
  • The array_count_values function then counts the occurrences of each word.
  • The script then calls the function with a sample sentence ($inputSentence) and prints the result using print_r for a formatted output.

Post your Answer