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.
PHP Code:
$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.
PHP Code:
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;
Bookmarks