Page 1 of 1

How 2 Count number words in a string.

Posted: Tue Feb 14, 2006 4:51 pm
by jclarkkent2003
Hi,
how to count # words in a string?

Code: Select all

$num_words_string = sizeof(explode(" ",$string));
only way? or is there an eaiser better way?

Posted: Tue Feb 14, 2006 5:07 pm
by Ree
It's ok if you're sure each word is separated by a single space. However, count() is more widely used, I think (functionality is the same as sizeof()).

Posted: Tue Feb 14, 2006 5:21 pm
by feyd
count() = sizeof(), sizeof() = count() (they're aliased)

ahem: str_word_count()

Posted: Tue Feb 14, 2006 6:49 pm
by jclarkkent2003
HAH, how did i not see that one in php.net.... That's where I am 90% of the day, lol...

Posted: Tue Feb 14, 2006 6:54 pm
by josh
Also as a general idea of how to find optimizations to things like this ( I know the function exists that does this for you but this applies to programming in general not just this function )

Look at what your code does, it splits on the space and then counts the elements, what this is basically doing is counting the number of spaces inside the string, so to optimize you would just count the number of spaces (instead of creating an array, then having the count function, etc.. which brings more overhead into the application)