DEV Community

Discussion on: How to count words in a string in PHP

Collapse
 
moopet profile image
Ben Sinclair • Edited

That second parameter is nasty. I would never expect a function explicitly called "word count" to return an array of words. It should only ever return the number of words it counts, and as such I'd never use that parameter.

Unfortunately, if you want to specify the definition of "word", you need the third parameter, which means when you call the function, you need to include a meaningless "0" as the second argument. This is a great example of why people don't like PHP!

If I wanted to extract all the words, I'd either use preg_match_all or strtok, simply to help readability for anyone unfamiliar with what magic numbers to include. PHP doesn't even have constants defined for the different options, it's a bare integer :/

The randomness of the use of underscores in strtok compared to str_word_count, or the difference in naming compared to the character-based version of this function (count_chars) is another reason people don't like PHP. It's almost better to make your own properly-named wrappers for everything.