In php, we can get the word count and number of words in a string with the str_word_count() function.
$string = "This is a string";
echo str_word_count($string);
// Output:
4
When working with string variables in our code, the ability to easily get information about the variables is valuable.
One such piece of information is the number of words in a string variable.
We can use the php str_word_count() function to get the number of words in a string in our php code.
Just pass the string variable to str_word_count() and you’ll get the word count.
Below is a simple example showing you how to get the word count of a string in php.
$string = "This is a string";
echo str_word_count($string);
// Output:
4
Using str_word_count() to Get an Array of All Words in a String
The php str_word_count() function, by default, returns the number of words in a string.
You can change the default behavior by passing a value to the optional ‘return’ parameter.
If you pass ‘1’ or ‘2’ to ‘return’, then you will get an array which contains the words of the string variable. Passing ‘1’ returns just the words. If you pass ‘2’, you get an array where the keys are the position of the word and the value is the word.
Below are some examples showing different ways you can use str_word_count() in your php code.
$string = "This is a string";
echo str_word_count($string);
echo str_word_count($string, 1);
echo str_word_count($string, 2);
// Output:
4
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
Array
(
[0] => This
[5] => is
[8] => a
[10] => string
)
Hopefully this article has been useful for you to learn how to get the word count of a string in php.