PHP Program to count the words in the string


April 3, 2022, Learn eTutorial
1264

How to find the number of words in the string?

In this program, we are counting the number of words in the string. To do that we are checking the white spaces and counting the words after that white space. For example, if consider "Hello world" as our string and we can see that white space is used to separate the words and the output will 2.

How to find the number of words in the string using PHP?

For this program, we are taking the static string and the string is directly assigned to the variable string. After that, we are assigning a value 0 to the variable count which will be used to store the count of words. Then we will assign the length of the string to the variable size after that we will assign the value 0 into the variable i and perform the for loop until the condition 'i < size -1' becomes false and also increment the value of the variable by 1 in every iteration and in the loop block we will check the conditions 'string[i] == " " ', 'ctype_alpha(string[i + 1])' and 'i > 0' if all these conditions are true then increment the value of variable count by 1. After the completion of the loop, we should increment the value of the variable count by 1 to count the last word. At last, we can print the string in the variable string as the entered string and print the value of the variable count as the count of the words in the string.

ALGORITHM

Step 1: Assign the string into the variable string

Step 2: Assign the value 0 into the variable count (variable to store the count of words)

Step 3: Find the length of the string and assign the value to the variable size

Step 4: Assign the value 0 into the variable i and perform the sub-steps until the condition 'i < size - 1' becomes false and increment the value of the variable i in every iteration

        (i) check the conditions 'string[i] == " " ' , 'ctype_alpha(string[i + 1])' and 'i > 0' if all these conditions are true then increment the value of variable               count by 1

Step 5: Increment the value of the variable count by 1 to count the last word

Step 6: Print the string in the variable string as the entered string and print the value of the variable count as the count of the words in the string

PHP Source Code

                                          <?php
$string = "welcome to learnetutorials.com where you train to be a programmer";
$count = 0;
$size = strlen($string);
for ($i = 0; $i < $size - 1; $i++) {
    if ($string[$i] == ' ' && ctype_alpha($string[$i + 1]) && ($i > 0)) {
        $count++;
    }
}
$count++;
echo "The entered string is: $string \n";
echo "Total number of words in the string is: $count";
?>
                                      

OUTPUT

The entered string is: welcome to learnetutorials.com where you train to be a programmer
Total number of words in the string is: 10