I’ve never really had use for functions in the past, but now I do, so I’m trying to learn using a basic one I found on the web. Can someone explain why the word count is not being returned? I must be missing something very basic.
Basically to cut the reason short it’s because your trying to call a variable in which doesn’t exist, when using functions the return variable is just a value of whatever your returning there for you need to assign a variable to the function call itself.
$words = count_words($str);
echo $words;
On a side note your regular expressions shouldn’t use the ereg(i) functions as they have been deprecated for a long time now, the preg family is what you should be using from now on. See the below code which i cleaned up a bit.
function count_words($str) {
$words = explode(' ', preg_replace('/[ ]{2,}/', ' ', $str));
$count = 0;
for ($i = 0; $i < count($words); $i++) {
if (preg_match('/[a-zA-Z0-9]+/', $words[$i])) {
$count++;
}
}
return $count;
}
$str = 'hello there';
$total = count_words($str);
echo 'The total number of words is: ' . $total;