HardCoreMore Posted December 29, 2010 Share Posted December 29, 2010 Is there a way to stop loop inside a switch or i must use if instead of switch? Example: <?php for( $i = 0; $i < 10; $i++ ) { switch( $i ) { case 1: break; case 2: // break from loop here break; case 3: break; } } ?> Thanks Quote Link to comment https://forums.phpfreaks.com/topic/222930-is-there-a-way-to-stop-loop-inside-switch/ Share on other sites More sharing options...
shlumph Posted December 29, 2010 Share Posted December 29, 2010 You could nest the operation inside of a function and return something when you want the operation to end. Quote Link to comment https://forums.phpfreaks.com/topic/222930-is-there-a-way-to-stop-loop-inside-switch/#findComment-1152673 Share on other sites More sharing options...
DavidAM Posted December 29, 2010 Share Posted December 29, 2010 break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. See the PHP online documentation for break So in your case it would be: for( $i = 0; $i < 10; $i++ ) { switch( $i ) { case 1: break; case 2: // break from loop here break 2; case 3: break; } } Quote Link to comment https://forums.phpfreaks.com/topic/222930-is-there-a-way-to-stop-loop-inside-switch/#findComment-1152679 Share on other sites More sharing options...
HardCoreMore Posted December 29, 2010 Author Share Posted December 29, 2010 break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. See the PHP online documentation for break So in your case it would be: for( $i = 0; $i < 10; $i++ ) { switch( $i ) { case 1: break; case 2: // break from loop here break 2; case 3: break; } } Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/222930-is-there-a-way-to-stop-loop-inside-switch/#findComment-1152692 Share on other sites More sharing options...
Zurev Posted December 29, 2010 Share Posted December 29, 2010 break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. See the PHP online documentation for break So in your case it would be: for( $i = 0; $i < 10; $i++ ) { switch( $i ) { case 1: break; case 2: // break from loop here break 2; case 3: break; } } Nice recommendation, I always used break to break out of loops, but never knew about the optional parameter! Quote Link to comment https://forums.phpfreaks.com/topic/222930-is-there-a-way-to-stop-loop-inside-switch/#findComment-1152697 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.