22nd January 2008 - 6 minutes read time
The str_word_count() function in PHP does exactly what is says it does. The default of this function is to simply count the number of words present. Take the following string.
$str = "This is a 'string' containing m0re than one word. This is a 'string' containing m0re than one word.";
If we pass this to the str_word_count() function with no other parameters we get the number of words.
echo str_word_count($str); // prints 20
The second parameter is the type of value returned from the function. The default value is 0, but 1 and 2 are also available. Using 1 as the second parameters returns an array containing all the words found inside the string. Using 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. Here are the results from setting the second parameter to 1.