Jump to content

Logic in Switch statement?


The14thGOD

Recommended Posts

Switch case logic is pretty simple here is a more thorough example:

 

<?php
$action = "post";

switch ($action) {
     case 'post':
          print "This is the post case selection";  
     break;

     case 'index': 
          print "This is the index case selection";
     break;

     default:
     case 'none':
           print  "This is the default/none case selection";
     break;

     case 'test1':
     case 'test2':
            print "Either test1 or test2 got you here!";
     break;
}

?>

 

It does not have to be words it can be integers etc. But basically it is like an if statement, just a different style, IE: IF $action is equal to a certain item than execute that until the break, at which point do not execute more code.

You Cant insert Contitions (!, ==, >, <, <=, >= ,etc..) in case just values.

you can enter condition in switch() only not in cases

Use

<?php
switch($variable){
case 0:
case 1:
..............
case 9:
case 10:
blah blah blah
break;
default:
echo 'Greater than 10 or smaller than 0';
}
?>

You Cant insert Contitions (!, ==, >, <, <=, >= ,etc..) in case just values.

you can enter condition in switch() only not in cases

Use

<?php
switch($variable){
case 0:
case 1:
..............
case 9:
case 10:
blah blah blah
break;
default:
echo 'Greater than 10 or smaller than 0';
}
?>

 

not completly true... if you

switch(true){

case "$v<6":

break;

}

it will take... basically the switch will grab the first case in which the "$v<6"===true

CONDITIONS CANNOT STAY IN CASE.

CONDITIONS ALWAYS STAY IN switch()

and if your contition in switch() is true. with respecty to respective cases / default cases. it will go through that class.

and here switch is already true. no conditions at all. and as there is only 1 case it is entering in that case caues there is nothing to make it false.

Yes it will work.

<?php
$v = 8;
switch(true){
case $v<6:
  echo 'Entering into case 1';
break;
case $v>6:
  echo 'Entering into case 2';
break;
default:
  echo 'Entering into default case';
}
?>

But here also the condition is not in the CASE(s).

Here the condition is in switch and the condition is true.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.