Backend Development 3 min read

PHP str_word_count() Function – Description, Parameters, Return Values, and Usage Examples

This article explains PHP's str_word_count() function, detailing how it counts words in a string, the optional format and charlist parameters, the possible return types (integer or array), and provides multiple code examples demonstrating different usage scenarios.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP str_word_count() Function – Description, Parameters, Return Values, and Usage Examples

Function Overview The str_word_count() function returns information about the words used in a given string. By default it returns the number of words as an integer, but with the optional format parameter it can return an array of words, an associative array of word positions, or both.

Parameters

string – The input string to be analyzed.

format – Determines the type of return value. Supported values are: 0 – Return only the word count (integer). 1 – Return an indexed array containing all words. 2 – Return an associative array where keys are the numeric positions of the words in the string and values are the words themselves.

charlist – (Optional) A string of additional characters to be considered part of a word.

Return Value Depending on the format argument, the function returns either an integer (word count) or an array (list of words or word positions).

Example Code

Sample Output

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)
Array
(
    [0] => Hello
    [6] => fri3nd
    [10] => you're
    [29] => looking
    [46] => good
    [51] => today
)
7

The examples illustrate how different format values affect the output, and how the optional charlist can be used to treat additional characters as part of words.

Backendstring-functionsphp-functionsstr_word_countword count
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.