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>";
?>