Word Frequency Counter
Write a PHP function that counts how many times each word appears in a string. Return an associative array mapping words to their counts. The comparison should be case-insensitive.
Use strtolower() to normalize the entire string to lowercase first. Then str_word_count() with mode 1 returns an array of all individual words found in the text. Loop through the words array and use an associative array to track counts.
PHP's associative arrays make this natural: $counts[$word] = ($counts[$word] ?? 0) + 1 uses the null coalescing operator to handle the first occurrence of each word. The resulting array maps each distinct word to its frequency.
Edge cases include empty strings (return empty array), words with punctuation, varying capitalization, and strings with only one word.
Time complexity is O(n) where n is the string length. Space complexity is O(m) where m is the number of unique words.
Word frequency analysis is a common task in natural language processing and text analytics. PHP's str_word_count() function automatically handles word boundaries, making it more reliable than a simple explode() that would miss punctuation handling.
PHP's null coalescing operator ?? provides a clean default value when accessing array keys that may not exist, eliminating the need for isset() checks in simple cases.Example Input & Output
Algorithm Flow

Solution Approach
Write a PHP function that counts how many times each word appears in a string. Return an associative array mapping words to their counts. The comparison should be case-insensitive.
Use strtolower() to normalize the entire string to lowercase first. Then str_word_count() with mode 1 returns an array of all individual words found in the text. Loop through the words array and use an associative array to track counts.
PHP's associative arrays make this natural: $counts[$word] = ($counts[$word] ?? 0) + 1 uses the null coalescing operator to handle the first occurrence of each word. The resulting array maps each distinct word to its frequency.
Edge cases include empty strings (return empty array), words with punctuation, varying capitalization, and strings with only one word.
Time complexity is O(n) where n is the string length. Space complexity is O(m) where m is the number of unique words.
Best Answers
<?php
function wordFrequency($text) {
$w=str_word_count(strtolower($text),1);$c=[];foreach($w as $x){$c[$x]=($c[$x]??0)+1;}return $c;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
