Code Logo

Word Frequency Counter

Published at24 Jul 2026
PHP String Handling Medium 0 views
Like0

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

Example 1
Input
"the cat and the dog"
Output
{"the":2,"cat":1,"and":1,"dog":1}
Example 2
Input
""
Output
{}
Example 3
Input
"Hello hello"
Output
{"hello":2}
Example 4
Input
"PHP"
Output
{"php":1}
Example 5
Input
"a A a"
Output
{"a":3}

Algorithm Flow

Recommendation Algorithm Flow for Word Frequency Counter
Recommendation Algorithm Flow for Word Frequency Counter

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 - Approach 1
<?php
function wordFrequency($text) {
    $w=str_word_count(strtolower($text),1);$c=[];foreach($w as $x){$c[$x]=($c[$x]??0)+1;}return $c;
}