How to Count Words in PHP - str_word_count() Function

PHP String Functions

The str_word_count() function returns the number of words inside string.

Syntax

str_word_count(string $string, int $format = 0)

If the optional format is not specified, then the return value is an integer representing the number of words found.

If the format is specified, then the return value is an array.

  • 0 - returns the number of words found
  • 1 - returns an array containing all the words found inside the string
  • 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself

Examples

Example 1: Counting words in a string

$string = "Hello, World!"; 
$count = str_word_count($string);
echo $count;

Output: 2

Example 2: Getting an array of words

$string = "The quick brown fox";
$words = str_word_count($string, 1);
print_r($words);

Output: Array ( [0] => The [1] => quick [2] => brown [3] => fox )