Last updated on March 15, 2023
The str_word_count() function counts the word of the provided string and returns the result in an integer. For example, if you pass the Hello Word into the function then it would return 2.
Syntax
str_word_count($string);
Parameters
It has a required parameter that refers to the string that words needed to count.
Example 1
echo str_word_count("software engineer");
// Output: 2
In this example, a string is passed into the str_word_count() function as an argument for counting the words. The function returns 2 with the integer data type, which is because the string contains 2 words, and the str_word_count() function returns the integer value.
Example 2
$favorite = "PHP is my favorite programming language.";
echo str_word_count($favorite);
// Output : 6
In this example, the string is stored in the favorite variable and in the next line of the above code it is passed into the function as an argument. The str_word_count() counts words from the string and returns the result with the integer data type.