The str_word_count() function is used to count the number of words in a string. This function was introduced in PHP4. The value of format dictates the returned value:
|0 (default)||The number of words found in string|
|1||An array of all words found in string|
|2||An associative array, with keys being the positions and values being the words found at those positions in string|
str_word_count(string $string, int $format = 0, ?string $characters = null): array|int
The str_word_count() function returns the number of words in a string. You can pass a second parameter to str_word_count() to make it do other things, but if you only pass the string parameter by itself, then it returns the number of unique words that were found in the string.
|format||Specify the return value of this function. (0 or 1 or 2)|
|characters||A list of additional characters which will be considered as ‘word’|
Returns an array or an integer, depending on the format chosen.
<?php $text = “Good morning friends! have nice day”; $a=str_word_count($text,1); $b=str_word_count($text,2); $c=str_word_count($text); print_r($a); print_r($b); print $c; ?>
The output of the above program is as follows:
Array (  => Good  => morning  => friends  => have  => nice  => day ) Array (  => Good  => morning  => friends  => have  => nice  => day ) 6