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:


$str = "Find number of words in this sentence";
$count = str_word_count($str);

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


<html>
<head>
	<title>
		Count number of words using PHP
	</title>
</head>
<body style="text-align: center;">
	<h1 >PHP program to count number of words in a Sentence</h1>
	<?php 
	$str = "Find number of words in this sentence";
	$count = str_word_count($str);
	echo "<h2>Number of words in the sentence - \"$str\" is = <span style='color:blue;'>".$count."<span></h2>";
	?>
</body>
</html>

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) function counts the number of words. Let us name this file as index.php and save it in a folder "word_count" under htdocs.

word count in phpTest the Application

Run localhost/word_count in the browser. You will see the page opened with count displayed in blue color.

Word Count in PHP

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


<html>
<head>
	<title>
		Count number of words using PHP
	</title>
</head>
<body style="text-align: center;">
	<h1 >PHP program to count number of words in a Sentence</h1>
	<?php 
	$str = "Find number of words in this sentence";
	$arr = str_word_count($str,1);
	for ($i = 0;$i<count($arr);$i++)
		echo $arr[$i].' ';

		echo "<br>";
		echo "No. of words = ".$i;
	
	?>
</body>
</html>

This time while calling the function str_word_count(), we used a format "1" as another parameter. 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 phpNote

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 the associative array.