Open In App

PHP str_word_count() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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 , $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:

  • Calculating the number of words in a string: To Display only the number of words in a string,the str_word_count() function should be executed in the following way: 

php




<?php
$mystring = "Twinkle twinkl4e little star";
print_r(str_word_count($mystring));
?>


Output:

5
  • Find the words in a string: To return an array containing the words in a string,the str_word_count() function should be executed in the following way: 

php




<?php
$mystring = "Twinkle twinkl4e little star";
print_r(str_word_count($mystring, 1));
?>


Output:

Array ( [0] => Twinkle [1] => twinkl [2] => e [3] => little [4] => star )
  • Find words in a string along with numeric position of the words: To return an array containing the words in a string along with numeric position of the words,the str_word_count() function should be executed in the following way: 

php




<?php
$mystring = "Twinkle twinkl4e little star";
print_r(str_word_count($mystring, 2));
?>


Output:

Array ( [0] => Twinkle [8] => twinkl [15] => e [17] => little [24] => star ) 
  • Find words in a string when some special character are considered as word: To return an array containing the words in a string where a character shall be considered as a word, the str_word_count() function should be executed in the following way: 

php




<?php
$mystring = "Twinkle twinkl4e little star";
print_r(str_word_count($mystring, 2 ,4));
?>


Output:

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


Last Updated : 21 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads