PHP: str_word_count() function


The str_word_count() function is used to count the number of words in a string.


(PHP 4 and above)


str_word_count(string_name, nformat, add_chars)


Name Description Required /
string_name The input string. Required String
nformat Specifies the return value of the str_word_count() function.
Supported values :
0 - returns the number of words found.
1 - returns an array contains all the words found within the specified string.
2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself.
Optional Integer
add_chars A list of additional characters which will be considered as 'word'. Optional String

Return value:

An array or an integer, depending on the format chosen.

Value Type: Mixed.

*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Pictorial Presentation



$string_name='Welcome to w3resource.com';
echo '<br>';
echo '<br>';

Output :

Array ( [0] => Welcome [1] => to [2] => w [3] => resource [4] => com )
Array ( [0] => Welcome [8] => to [11] => w [13] => resource [22] => com )

View the example in the browser

See also

PHP Function Reference

Previous: str_split
Next: strcasecmp

PHP: Tips of the Day

PHP: How to write to the console in PHP?


On Firefox you can use an extension called FirePHP which enables the logging and dumping of information from your PHP applications to the console. This is an addon to the awesome web development extension Firebug.

  • http://www.studytrails.com/blog/using-firephp-in-firefox-to-debug-php/


However if you are using Chrome there is a PHP debugging tool called Chrome Logger or webug (webug has problems with the order of logs).

More recently Clockwork is in active development which extends the Developer Tools by adding a new panel to provide useful debugging and profiling information. It provides out of the box support for Laravel 4 and Slim 2 and support can be added via its extensible API.

Using Xdebug

A better way to debug your PHP would be via Xdebug. Most browsers provide helper extensions to help you pass the required cookie/query string to initialize the debugging process.

  • Chrome - Xdebug Helper
  • Firefox - The easiest Xdebug
  • Opera - Xdebug
  • Safari - Xdebug Toggler

Ref : https://bit.ly/3ck9rFg