Question

I've been trying to teach myself php and I came across this code (as with all code I try it out myself to get a better understanding etc) but this one doesn't run.

<?php 
$i = 0; 
while($i++){
 switch ($i) { 
 case 5: 
 echo "At 5<br />"; 
 break 1; 
 case 10: 
 echo "At 10; quitting<br />"; 
 break 2; 
 default: 
 break; 
 } 
}
 ?> 

The output is just blank but would i be correct in saying that $i is incremented until it hits 5, at which point switch($i) would go to case 5 at echo "At 5" and then it'll break that switch statement and continue in the while loop incrementing $i till it reaches 10, then it'll repeat the same process and go to echo "At 10; quitting" and the break 2 would leave the switch and while loop?

During all the other values for $i i'm assuming it goes to default and just breaks out of the switch

Thank You.

Was it helpful?

Solution

The problem is this:

$i = 0; 
while($i++){

When you do $i++ the variable $i is incremented with one but the value that is returned is still the old value, see the manual on Incrementing/Decrementing operators. So the first time when $i is still 0, the condition evaluates to false and the whole while() loop is never run / your switch is never reached.

To increase first and then return the value, you do:

$i = 0; 
while(++$i){

See the example.

OTHER TIPS

Try and make your code more readable by using variables/constants instead of magic numbers and you can also use labels on loops to break/continue on. Here is an example for you:

define("SOMETHING", 5);
define("SOMETHING_ELSE", 10);

$count = 0;

mainLoop:
while($count < 100) { #loop virtually forever

  switch(++$count) { #increment and switch on $count in each iteration

      case SOMETHING: #$count = 5
          #do something here
          echo "At 5<br />";
          break; #break switch, continue while loop

      case SOMETHING_ELSE: #$count = 10
          #do something else here 
          echo "At 10; quitting<br />";
          break mainLoop; #break while loop

  }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top