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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable scopes in Switch statements

Status
Not open for further replies.

TheQuestioner

Programmer
Jun 29, 2002
78
GB
Greetings my fellow coding overlords.

I have slight problem with a PHP page that I am currently coding. I'm trying to determine the value of a specific variable using the SWITCH statement, and then altering the value of this same variable within the SWITCH statement. However I can't seem to change the value. My code is as follows

Code:
<?PHP
  //some processing happens here

  //store GET POST value into variable
  //(This should be numeric)
  $intOrder= $_GET["order"];

  //validate passed column val
  switch ($intOrder)
  {		
    case $intOrder==(3||7||9): //other columns
	 break;
			
    case $intOrder==(4||8): //date columns
	 [highlight]$intOrder.=" DESC";[/highlight]
	 break;
			
    //any other value, then default to sort by gallery    
    //description	
    default:
	   $intOrder="4 DESC";
	   break;
  };

  echo $intOrder;
?>

Generally the code works, but if I pass in 4 or 8, I'm expecting it to show

Code:
4 DESC

or

Code:
8 DESC

but I only get a number returned. Has this got something to do with variable scoping? Or does PHP automatically convert the variable into a number type?
 
TheQuestioner,

Actually I'm just a vassal (not an overlord) around here but I think the answer may be in the grouping like:

Code:
  switch ($intOrder)
  {        
    case 3:
    case 7:
    case 9: //other columns
     break;
            
    case 4:
    case 8: //date columns
     $intOrder.=" DESC";
     break;
            
    //any other value, then default to sort by gallery    
    //description    
    default:
       $intOrder="4 DESC";
       break;
  };


Keep in mind, in a switch statement you are testing a variable not an expression.


Hope it's helpful.

Good Place to "Learn More">>
 
Excellent Lrnmore, this has worked perfectly. I hereby promote you to Overlord.
 
Some more background:
The nature of the switch statement is that the expression is only evaluated once, at the top. The individual cases mereley list the possible outcomes, but do not evaluate any expressions. Only if / elseif statements operate that way.
The code works the way Lrnmore suggested by the default that only a break statement will exit the switch. An 'OR' like comparison can be made that way by listing the desired outcomes in successive case statements and exitign after the last of the group with a break.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top