How to count the number of words in a string using PHP

You can count the number of words in a given srting using PHP string function str_word_count(). See the below code:

Using this PHP string function, you can print number of words in a sentence in a php program. See the below code which prints the number of words in a string:

We are using a PHP variable $str to hold the input string, number of words of which we want to count. In the next line, str_word_count($str) is counting the number of words. Then, we are displaying the count. Let us name this file as index.php and save it in a folder "word_count" under htdocs.

word count in phpTest the Application

Make sure in your XAMPP control panel Apache and MySQL services are running. Open the browser and run localhost/word_count. You will see the page opened with count displayed in blue color.

Word Count in PHP

Now, let us change the above code little bit. See below:

This time while calling function str_word_count(), we used a format "1". Default is "0" which counts the number of words. But, if we specify the format as "1", it returns an array with all the words in the sentence. So using a for loop we are displaying the words from the array. Now, if you save it as word_count.php and run it in browser, it will display the input string itself and the count of words in the string. See below output:

Word Count in PHP

word codunt in phpImportant Note

You can also use format as "2" in the function. In that case it will return an associative array. Just use the index and corresponding word as value to display from associative array.

word codunt in phpConclusion

This is an example of using string function in PHP. There are many useful string functions available in PHP, you can use them during PHP programming.