Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Switch CASE with Multiple Case values!! Pls Help 2

Status
Not open for further replies.

Forri

Programmer
Joined
Oct 29, 2003
Messages
479
Location
MT
Hi all

i'm trying to activate a script on a condition using switch; my problem is that if the case has 2 values which if the both are true it does not work:

Code:
switch ($ID)
{
 case 1:
   echo "1";
   break;

 case (2 || 3):
   echo "2 or 3"; 
   break;

 case (4 || 5):
   echo "4 or 5";
   break;
}

now if i try to send an ID of 1 the answer is 1
if i try 2 or 3 the anser is 2 or 3
but if i try 4 or 5 then the answer is still 2 or 3

i'm assuming that its not reconising the condition correctly!

How can i correct this? i've somewhere read that this does not work on a Windows 2000 OS, Apache is it true?

Thanks
Ncik
 
Code:
switch (true)
{
 
  case preg_match('/1/',$ID,$match):
    echo "should be 1 ($match[0])"; 
   break;

 case preg_match('/2|3/',$ID,$match):
   echo "should be 2 or 3 ($match[0])"; 
   break;

 case preg_match('/4|5/',$ID,$match):
   echo "4 or 5 ($match[0])";
   break;
}

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
That's a lot of code to get around using simple if statements.
It will not work the way you think it should:
The case statement always evaluates first. The expression 2 || 3 always evaluates as true, since both of them are not 0 (zero). That also means that the comparison with any other value than 0 (zero) will be true.
Your case with the value 1 only works because you literaly compare the value. All other values (except zero) will be caught by the second case.
Switch works like this:
Code:
# case result compared to switch
true == $ID;
# not switch compared to case
$ID == (2 || 3);
 
I would just make use of the fact that a switch statement will, once it has chosen an entry point, continue to process commands until it hits a "break;" or the closing braces of the block:

switch ($foo)
{
case 1:
do_something();
break;
case 2:
case 3:
do_something_else();
break;
case 4:
case 5:
case 6:
do_this_third_thing();

}



Want the best answers? Ask the best questions!

TANSTAAFL!!
 
A star for Sleipnir as I didn't realise you could do :
Code:
  case 4:
  case 5:
  case 6:
      do_this_third_thing();

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Great Sleipnir!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top