cl0udw4lk3r
cl0udw4lk3r

Reputation: 2733

PHP switch falling though issue

Code:

switch ($_GET['operation']) {
    case "professionist":
    case "company":
    case "student":
        echo "ok<br>";

    case "professionist":
        echo "inprofessionist<br>";
        break;

    case "company":
        echo "incompany<br>";
        break;

    default:
        echo "Meh!<br>";
        break;
}

My goal is to execute some (common to professionist/company/student) code first, and then execute the rest of the code depending on the operation...

The problem is that the first 3 cases works perfectly, but then, if for example the operation is "company", the switch go on "professionist" case, what i'm doing wrong? How can improve that? Thanks in advance...

Upvotes: 0

Views: 68

Answers (2)

Denis Ermolin
Denis Ermolin

Reputation: 5546

That's how switch works. If you always need to print "ok" then move it outside switch:

$op = $_GET["operation"];

if (in_array($op, array("professionist", "company"))) {
   echo "ok<br>";
}

switch ($op) {
    case "professionist":
        echo "inprofessionist<br>";
        break;

    case "company":
        echo "incompany<br>";
        break;

    default:
        echo "Meh!<br>";
        break;
}

Upvotes: 3

Amber
Amber

Reputation: 527023

Only the first case with a given value will ever be targeted by a switch. (And in fact, a switch only ever goes to a single case per execution - fallthough just lets you have multiple cases share some code, but only one of them is what's actually triggered.)

Thus, it doesn't make sense to have multiple casees with the same value that they're looking for - a switch statement isn't the same thing as a series of independent ifs; it's a mapping of jump targets.

Essentially, let's say you have a switch like this:

w;                               // 001
switch ($foo) {                  // 002
  case 'a':
     w;                          // 003
  case 'b':
     x;                          // 004
     break;                      // 005
  case 'c':
     y;                          // 006
}
z;                               // 007

What actually winds up effectively happening is that you get some code effectively like this (note: highly simplified from how this actually works):

001  v
002  jump based on $foo: [a -> 003, b -> 004, c -> 006]
003  w
004  x
005  jump to 007
006  y
007  z

and then that program just gets run from top to bottom.

  • In the case where $foo is 'a', it jumps to 003 and runs from there, which means that it winds up doing v,jump,w,x,z in total.
  • In the case where $foo is 'b', it jumps to 004 and runs from there, which means that it winds up doing v,jump,x,z in total.
  • In the case where $foo is 'c', it jumps to 006 and runs from there, which means that it winds up doing v,jump,y,z in total.

Upvotes: 2

Related Questions