In this tutorial, you shall learn how to count number of words in a string in PHP using str_word_count() function, with examples.

PHP String – Count Number of Words

To count number of words in a string, in PHP, you can use str_word_count() function. Pass the string as argument to str_word_count() and the function returns an integer representing number of words in the string.

Examples

1. Find number of words in string

In the following example, we will take a PHP String literal and find the number of words in it using strlen() function.

PHP Program

</>
Copy
<?php
$str = 'Welcome to TutorialKart';
$count = str_word_count($str);
echo $count;
?>

Program Output

PHP String - Count Number of Words

Conclusion

In this PHP Tutorial, we learned how to find the length of a string using str_word_count() function.