Note that there are some explanatory texts on larger screens.

plurals
  1. POComparing equivalent if/else and switch loop
    primarykey
    data
    text
    <p>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.</p> <p>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 :)</p> <p>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!</p> <pre><code>&lt;?php $playerA=0; $playerB=0; $winA=0; $winB=0; $pair=0; while ($winA&lt;=2 &amp;&amp; $winB&lt;=2 &amp;&amp; $pair&lt;=15) { $playerA = rand(0,1); $playerB = rand(0,1); if ($playerA &gt; $playerB) { $winA ++; $winB=0; echo "&lt;div&gt;Player A Wins.&lt;/div&gt;"; } elseif ($playerA &lt; $playerB) { $winB ++; $winA=0; echo "&lt;div&gt;Player B Wins.&lt;/div&gt;"; } elseif ($playerA == $playerB) { $pair ++; $winA=0; $winB=0; echo "&lt;div&gt;Pair, play again!&lt;/div&gt;"; } } echo "&lt;div&gt;There is a total of {$pair} pair matches&lt;/div&gt;"; ?&gt; </code></pre> <p>And now the switch one...</p> <pre><code>&lt;?php $playerA=0; $playerB=0; $winA=0; $winB=0; $pair=0; while ($winA&lt;=2 &amp;&amp; $winB&lt;=2 &amp;&amp; $pair&lt;=15) { $playerA = rand(0,1); $playerB = rand(0,1); switch ($playerA &amp;&amp; $playerB): //This is an error: it should have been switch(true) case ($playerA &gt; $playerB): $winA++; $winB=0; echo "&lt;div&gt;Player A Wins.&lt;/div&gt;"; break; case ($playerA &lt; $playerB): $winB++; $winA=0; echo "&lt;div&gt;Player B Wins.&lt;/div&gt;"; break; case ($playerA == $playerB): $pair++; $winA=0; $winB=0; echo "&lt;div&gt;Pair, Play again!&lt;/div&gt;"; break; endswitch; } echo "&lt;div&gt;There is a total of {$pair} pair matches&lt;/div&gt;"; ?&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload