Answer:
<?php
function word_count($string){ // function that takes a string a parameter and returns the number of words in that string
$space = 0; // this variable is used in order to detect space, new line and tab spaces in a string
$words = 1;
// this variable is used to identify word presence in string
$include = $space; //used to maintain the state of $words and $space
$counter = 0; // this counts the number of words in the string
$i = 0; //this moves through each character of the string
while ($i < strlen($string)){ // iterates through every character of string until the last character of string is reached
if ($string[$i] == " "||$string[$i] == "\n" || $string[$i] == "\t") //if the space or new line or tab space is identified in the string
$include = $space; //set the state of include as space if the next character is a space newline or a tab space
else if ($include == $space) { //if next character is a word and current state i.e. $include holds $space
$include = $words; // then set the state i.e. $include as $words
++$counter; }
//increments i to move to next character at each iteration
++$i; }
//returns the number of words in a string
return $counter; }
$str = "Hello, how are you "; //sample string
echo "Words: " . word_count($str); // calls word_count function to return number of words in str.
?>
Explanation:
The program has a function word_count that accepts a string as its parameter and returns the number of words in the string. In the function there are three variables $space and $words and $include used as state variables. For instance $space identifies space, new line and tab spaces in the $string so it specifies that a space has occurred. $words identifies words in the $string so it specifies that a word has occurred. $include holds this state information. $i moves through every character of the $string and when a space occurs in the $string then the state $include is set to $space. When a word occurs then state $include is set to $words. $counter variable, which is used to count the number of words is incremented to 1 when previous state is $space and next character is a word character. Every time a word is seen in the string, this variable is incremented to 1 to keep track of number of words in the string. When $i reaches the end of the string then this loop stops and counter returns the number of words in the $string.