1

During an exercise I combined a while loop with an if/else clause, and thus decided to convert the if/else to use switch statement instead, just to challenge my mind.

The program is simple: there are two players that have to win 3 consecutive matches to stop the game. The players values are sorted randomly between 0 and 1, and there is a cap to the pair matches, just in the case randomness would ever win the race :)

I would like to understand which one is the best solution, and why, because to me it seems just that the switch version needs few lines of codes more!

<?php
$playerA=0;
$playerB=0;
$winA=0;
$winB=0;
$pair=0;
    while ($winA<=2 && $winB<=2 && $pair<=15) {
        $playerA = rand(0,1);
        $playerB = rand(0,1);
            if ($playerA > $playerB) {
                    $winA ++;
                    $winB=0;
                    echo "<div>Player A Wins.</div>";
            } elseif ($playerA < $playerB) {
                    $winB ++;
                    $winA=0;
                    echo "<div>Player B Wins.</div>";
            } elseif ($playerA == $playerB) {
                    $pair ++;
                    $winA=0;
                    $winB=0;
                    echo "<div>Pair, play again!</div>";
            }

    }
    echo "<div>There is a total of {$pair} pair matches</div>"; 
?>

And now the switch one...

<?php
$playerA=0;
$playerB=0;
$winA=0;
$winB=0;
$pair=0;
    while ($winA<=2 && $winB<=2 && $pair<=15) {
        $playerA = rand(0,1);
        $playerB = rand(0,1);
            switch ($playerA && $playerB): 
            //This is an error: it should have been switch(true)
                case ($playerA > $playerB):
                    $winA++;
                    $winB=0;
                    echo "<div>Player A Wins.</div>";
                    break;
                case ($playerA < $playerB):
                    $winB++;
                    $winA=0;
                    echo "<div>Player B Wins.</div>";
                    break;
                case ($playerA == $playerB):
                    $pair++;
                    $winA=0;
                    $winB=0;
                    echo "<div>Pair, Play again!</div>";
                    break;
            endswitch;

    }
    echo "<div>There is a total of {$pair} pair matches</div>";
?>
frafor
  • 139
  • 1
  • 11

5 Answers5

1

It's up to you, whichever is more readable for you. For me the first one is cleaner.

But in your example the function isn't the same: Instead of switch(true) you check for $playerA && $playerB which means that if $playerA or $playerB is 0 the first case which is false gets executed.

  • Thanks for the answer :) I was using switch(true) before, but then i've read somewhere that it can be considered a misuse of the switch statement. However, if && works as you say, then why i get A or B to win something when executing the code? Shouldn't i get always a pair match? – frafor Oct 11 '13 at 11:57
  • A && B gets evalueted to true, so (if A != 0 and B != 0) it's the same as switch(true). Using expressions in cases could generally be called a "misuse". –  Oct 11 '13 at 12:02
  • Yes, but if A and B are both !=0 it means they're both 1, since rand(0,1). So then why i don't get always a pair case, executing that code? – frafor Oct 11 '13 at 12:13
  • Given the case `A = 0` and `B = 1` then you switch for false (0 && 1 == false). `($playerA > $playerB) == false` is true and Player A wins –  Oct 11 '13 at 12:16
  • OOOooooooWaaaaaaaoooo... i've got it! :) – frafor Oct 11 '13 at 12:20
0

It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!

Reference: What is the relative performance difference of if/else versus switch statement in Java?

Switch may (depending on the implementatin) use jump table (in c and c++), so under certain conditions it may be more performant. Generally, it states your intention more clear so compiler can pretend it's smart.

considering if in your example doesn't even use else if chain, it makes switch even faster (because of not evaluating all conditions) and also may change the meaning of your code

If vs. Switch Speed

if-switch-performance So accourding to this exmple if is better.

Community
  • 1
  • 1
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
0

You should use switch, much of the time for readability and scalability issue, basically all you can do with switch also you cand do with else if block.

But in your example, because you test in switch two variable (player A and player B), switch statement will not give your code better readability. My choose is for else if block.

Also is good to remember that is good to use switch when you want to compare the same variable with another values several times like:

switch ($a) {
    case 0:
        echo "a = 0";
        break;
    case 1:
        echo "a = 1;
        break;
    case 2:
        echo "a = 2";
        break;
}

You can see that a is compared three times.

I hope i clarify your question.

Cristian Bitoi
  • 1,557
  • 1
  • 10
  • 14
0

Given that switch/case is always reproducible with an if/else construct, you should use it when it shines. It's way clearer when the switch portion has a fixed value or the result of an expression and then you check which "case" that value represents.

e.g.

$year_born = 2000;
switch ($age = get_current_year() - 2000){
   case $age < 18:
      // do something
      break;
   case $age >= 18 && $age <=20:
      // do something
      break;
   case $age > 20:
      // do something
      break;
}

You can rewrite it with an if but it's obvious here that you always do something related to the possible values of age. I don't expect this same pattern in an if/else.

Nobody however stops you from using them in another way, but I think this is a good coding style

Riccardo Galli
  • 12,419
  • 6
  • 64
  • 62
-1

Essentially, using a switch is fairly better than a "long if". Second code would be considered more polite but in terms of code, it's pretty the same.

zeyt
  • 39
  • 4