Page 1 of 1

A simple bit of code not counting correctly.

Posted: Wed Aug 30, 2006 4:31 pm
by impulse()
I have written this snippet of code for counting vowels in a string.

Code: Select all

unset($A);
unset($E);
unset($I);
unset($O);
unset($U);

$text = $_REQUEST["text"];

for ($i = 0; $i < strlen($text); $i++) {
   if ($text[$i] = "a" or "A") {
     $A += 1;
    }
   else if ($text[$i] = "e" or "E") {
     $E += 1;
    }
   else if ($text[$i] = "i" or "I") {
     $I += 1;
    }
   else if ($text[$i] = "o" or "O") {
     $O += 1;
    }
   else if ($text[$i] = "u" or "U") {
     $U += 1;
  }
}  
   
echo "<b>A:</b> $A<br>";
echo "<b>E:</b> $E<br>";
echo "<b>I:</b> $I<br>";
echo "<b>O:</b> $O<br>";
echo "<b>U:</b> $U<br>";
But it always always returns $A as 1. Even if there are no vowels in the string. Any ideas what's going on here?

Regards, Stephen

Posted: Wed Aug 30, 2006 4:52 pm
by feyd
= vs ==

and the logic of "a" or "A" doesn't function like you are apparently expecting it to.

Posted: Wed Aug 30, 2006 5:02 pm
by impulse()
I've figured it out mate.

Suppose I was looking for something like

Code: Select all

if ($text[$i] == "a" or $text[$i] == "A") {
Cheers for the help also.

Posted: Wed Aug 30, 2006 6:14 pm
by jayshields
Why not use:

Code: Select all

if(strtoupper($text[$i]) == 'A') {

Posted: Wed Aug 30, 2006 8:40 pm
by RobertGonzalez
That is what I was thinking...