PHP str_word_count() Function (original) (raw)

Last Updated : 21 Jun, 2023

The str_word_count() function is a built-in function in PHP and is used to return information about words used in a string like total number word in the string, positions of the words in the string etc.

Syntax:

str_word_count ( string,string , string,returnVal, $chars )

Parameters Used:

  1. **$string:**This parameter specifies the string whose words the user intends to count.This is not an optional parameter.
  2. **$returnVal:**The return value of str_word_count() function is specified by the $returnVal parameter. It is an optional parameter and its default value is 0. The parameter can take below values as required:
    • **0 :**It returns the number of words in the string $string.
    • **1 :**It returns an array containing all of the words which are found in the string.
    • **2 :**It returns an associative array with key-value pairs, where the key defines the position of the word in the string and the value is the word itself.
  3. **$chars:**This is an optional parameter which specifies a list of additional characters which shall be considered as a ‘word’.

Return Type: The return type of function depends on the parameter $returnVal and return the values as described above.

Below programs explain the working of str_word_count() function:

`

Output:

5

`

Output:

Array ( [0] => Twinkle [1] => twinkl [2] => e [3] => little [4] => star )

`

Output:

Array ( [0] => Twinkle [8] => twinkl [15] => e [17] => little [24] => star )

`

Output:

Array ( [0] => Twinkle [8] => twinkl4e [17] => little [24] => star )