vsingal5 vsingal5 - 3 months ago 17
PHP Question

Counter variable not working?

I'm writing a function to count syllables of a word as follows:

function estimate_syllables($word) {
$total_count=0;
foreach($word as $w) {
$syllable_count = count_english_vowels($w);
$total_count += $syllable_count;
}
return $total_count;
}

function count_english_vowels($word) {
static $english_vowels = array('A', 'E', 'I', 'O', 'U', 'Y');
$vowel_count = 0;
$letters = preg_replace('/[^a-z0-9]+/i', "", $word);
$len = strlen($letters);
$letters = str_split(strtoupper($letters));
$currPosition = -2;
$prevPosition = -1;
for($i = 0; $i < $len; $i++) {
if (in_array($letters[$i], $english_vowels)) {
if($i != $currPosition + 1) {
if ($letters[$i] == 'E' && $i != ($len -1))
$vowel_count++;

$prevPosition = $currPosition;
$currPosition = $i;
}
}
}
return $vowel_count;
}


I'm really confused: if you pass count_english_vowels a word like water, it reaches the inner loop to the correct syllable twice, yet the counter only reports a 1? Super confused, can anyone figure out what's going wrong?

Answer

It's only reporting one because of this:

if ($letters[$i] == 'E' && $i != ($len -1))
    $vowel_count++;
    $prevPosition = $currPosition; 
    $currPosition = $i;

There is only one E in water, thus it's only executing $vowel_count++; once. Based on your indenting of this code, I'd assume you need {} brackets around those lines, as without them PHP will only apply the first line after an if without them, so if that code is correct your indentation should look like this:

if ($letters[$i] == 'E' && $i != ($len -1))
    $vowel_count++;
$prevPosition = $currPosition; 
$currPosition = $i;