The first function I ever made does not work

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.

Thanks!

function count_words($str) {$words = 0;$str = eregi_replace(" +", " ", $str);$array = explode(" ", $str);for($i=0;$i < count($array);$i++){if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i])) $words++;}return $words;}

$str = "hello there";
count_words($str);
echo $words;

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;

Even though @chris_upjohn’s answer is perfect, there is no need to reinvent the wheel: [fphp]str_word_count[/fphp] :wink:

Thank you both!