106 of 410 menu

The str_word_count Function

The str_word_count function counts the number of words in a string.

The function can accept a second optional parameter, the number 1 or 2. If it is not specified, the function returns an integer equal to the number of words as its result.

If 1 is specified, an array containing all the words in the string is returned. If 2 is specified, an array is returned whose keys are the positions in the string, and the values are the corresponding words.

Syntax

str_word_count(string $string, int $format = 0, ?string $characters = null): array|int

Example

Let's count the number of words in a string:

<?php echo str_word_count('abcde my world'); ?>

Code execution result:

3

See Also

  • the substr_count function,
    which counts the number of substrings
  • the count_chars function,
    which counts the number of characters
  • the ucwords function,
    which converts the first letters of words to uppercase
byenru