PHP: Count Words in a String

A quick tip here for counting the number of words in a string. For example, when you need to determine if a submitted string is too short to be considered in inclusion or further processing.

$str = 'How to get the number of words in a string?';
$num = str_word_count($str, 0); // $num = 10

The PHP function str_word_count() is a weirdo in that the 2nd argument is a digit from 0 – 2. While it’s 0, str_word_count() counts and returns the total number of words in the string $str.

If it’s 1, str_word_count() returns an array of all the words identified inside the string $str.

Else if it’s 2, str_word_count() returns what it would return when it’s set to 1 but with all the keys being the numeric position of the corresponding word.

Scroll to Top