A simple bit of code not counting correctly.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

A simple bit of code not counting correctly.

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

= vs ==

and the logic of "a" or "A" doesn't function like you are apparently expecting it to.
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post 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.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

Why not use:

Code: Select all

if(strtoupper($text[$i]) == 'A') {
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

That is what I was thinking...
Post Reply