Given a string and we have to count the total number of words in it.
str_word_count() function
To find the total number of words in a string, we can use str_word_count() function – which is a library function in PHP – it returns the total number of words in the string.
Syntax:
str_word_count(string,return,char);
Here,
- string is a required parameter, this is the string in which we have to find the total number of words.
- return – it is an optional parameter used for specifying the return type – it can accept three values
- 0 – Which is the default value, it specifies the return the number of words in the string.
- 1 – It specifies the return of the array with the words.
- 2 – It specifies the return of the array where key is the position and value is the actual word.
- char – it is an optional parameter – it is used to specify a special character to consider as a word.
PHP code to count the total number of words in a string
Output
Explanation:
In PHP, We have the function str_word_count() to count the number of words in a string. We use the same to get the number of words in the string ($str) and store the output of the function in ($response) then use echo to print the result.
need an explanation for this answer? contact us directly to get an explanation for this answer