Create Function in PHP to Count Words in a String

One person has asked me to write a function in PHP to count number of words in a string.
You don’t have to use any inbuilt function in PHP except strlen and strpos.

Imagine if you have to do this problem using inbuilt PHP function. Then you can do
it easily through str_word_count(). You need to just pass the string and you get the word count.

In my previous post, i explained the logic to count number of words.

Logic of a Problem

To solve this problem, traverse the string character by character. If you don’t find space increment wordcount by 1, then reach at the end of a word to avoid multiple count of the same word.

Most Used Array Function in PHP

Function in PHP to Count Words in a String

If you have any other good method. You can suggest us in comment.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.