Skip to content

str_word_count()

The PHP str_word_count() function is used to count the number of words in a string. In this article, we will discuss the syntax and usage of str_word_count(), as well as provide some examples.

The syntax of the str_word_count() function is as follows:

The PHP syntax of str_word_count()

php
str_word_count($string, $format, $charlist)

The function takes three parameters: $string, $format, and $charlist. $string is the string to count the words in. $format is an optional parameter that specifies the format of the output: 0 returns the word count (default), 1 returns an array of words, and 2 returns an associative array where keys are word positions. $charlist is also an optional parameter that specifies additional characters to be considered as word characters.

Here is an example of how to use the str_word_count() function:

Example of PHP str_word_count()

php
<?php
$string = "The quick brown fox jumps over the lazy dog.";
$count = str_word_count($string);
echo $count; // Output: 9
?>

In this example, we have a string variable $string that contains the phrase "The quick brown fox jumps over the lazy dog.". We use the str_word_count() function to count the number of words in the string.

The output of this code will be:

console
9

As you can see, the str_word_count() function has successfully counted the number of words in the string.

To demonstrate the $format parameter:

php
<?php
$string = "Hello world!";
print_r(str_word_count($string, 1));
?>

The str_word_count() function is a useful tool for counting the number of words in a string in PHP. It can be used to analyze text input and perform operations that depend on the number of words. By mastering this function, you can become a more proficient PHP developer.

We hope this article has been helpful in understanding the str_word_count() function in PHP.

Practice

What does the PHP str_word_count() function do?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.