Count Words
Write a PHP function that counts the number of words in a given string. Words are sequences of characters separated by spaces. Multiple spaces should be handled correctly (counted as a single separator).
You can use PHP's built-in str_word_count() function which counts words in a string. Alternatively, use explode() to split by spaces and filter empty strings with array_filter().
This problem introduces PHP string functions. The function takes a string and returns the word count. Edge cases include empty strings (return 0), strings with only spaces (return 0), and strings with multiple spaces between words.
The word counting problem uses PHP string functions. str_word_count() counts words in a string, handling multiple spaces naturally. trim() removes leading/trailing spaces that would create empty word entries.
The word counting problem showcases PHP's string functions. str_word_count() is a PHP-specific function that counts words considering alphabetic characters. The trim() function removes whitespace from both ends, preventing empty strings from being counted. This problem demonstrates PHP's string handling strengths with built-in text processing functions.
Example Input & Output
Two words with leading spaces.
Two words.
Empty string.
Three words.
Single word.
Algorithm Flow

Solution Approach
Start by trimming the input string with trim() to remove leading and trailing whitespace. This prevents empty strings from being counted as words. If the trimmed string is empty, return 0 immediately.
The core of the solution uses str_word_count() with mode 0, which returns the number of words found in the string. This PHP-specific function recognizes alphabetic characters and handles multiple spaces automatically, making it more reliable than explode() for natural language text.
An alternative implementation uses explode(' ', $text) combined with array_filter() to remove empty strings that result from multiple consecutive spaces. The array_filter() callback function('strlen', ...) removes any empty strings, and count() on the filtered array gives the word count.
Edge cases include empty strings (return 0), strings with only whitespace (trim reduces to empty, return 0), strings with leading/trailing spaces (trim handles them), and strings with multiple consecutive spaces (str_word_count handles them natively while explode would need array_filter).
The time complexity is O(n) where n is the string length. The space complexity is O(n) for the intermediate word array created by str_word_count or explode.
Best Answers
<?php
function countWords($text) {
$trimmed = trim($text);
if ($trimmed === '') return 0;
return str_word_count($trimmed, 0);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
