Jump to content

Curly braces when breaking for loop?


Prince_Bert

Recommended Posts

I'm learning PHP from the book, PHP & MySQL in Easy Steps but when I reached the section on breaking loops I think the author is a bit unclear about how many braces are used and therefore I cannot get the code to work as it should. The trouble is he writes it in so many stages. This is the first for loop and nested inner loop. Do I need braces here??

 

<?php


for ( $i = 1 ; $i < 4 ; $i++ )


{
 for ( $j = 1 ; $j < 4 ; $j++ )


echo "Running i = $i and j = $j <br>" ;


}


?>

</body>
</html>
 
I assume the above is correct as it works OK.
 
 
However, when I try to add the break code it just will not work however I do it - with or without curly braces, or wherever else  the break statement in the code. I type it as follows:
 
{ 
 if ( $i == 2 && $j == 1 )

echo "Breaks inner loop when i = $i and j = $j <br>" ;
break ;

}

 

Can anyone help?? I have been stuck on this for nearly an entire day and have tried everything.

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/276782-curly-braces-when-breaking-for-loop/
Share on other sites

Without curly braces only the first line is in the loop. So your code is this:

 

<?php
for ( $i = 1 ; $i < 4 ; $i++ )
{
     for ( $j = 1 ; $j < 4 ; $j++ )
     {
          echo "Running i = $i and j = $j <br>" ;
          if ( $i == 2 && $j == 1 )
          {
               echo "Breaks inner loop when i = $i and j = $j <br>" ;
          }
          break ;
     }
}
?>
Just use them. It will be easier for you to read. Use them and indent.

Thanks Jessica. That still does not display like the book says it should. I am getting

 

 

Running i = 1 and j = 1 
Running i = 2 and j = 1 
Breaks inner loop when i = 2 and j = 1 
Running i = 3 and j = 1

 

 

However, that is not showing the complete loop as it should be before and after the break. Am I using the wrong software. I have Notepad, but I am not sure whether I should have a different version for PHP. Something just isn't right.  :shrug:

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.