Created
September 14, 2011 23:22
-
-
Save jrtashjian/1218093 to your computer and use it in GitHub Desktop.
short-circuiting loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Improper: | |
* - can become hard to read if the else block is large | |
* - anytime you indent you decrease legibility. | |
* - only applicable for this instance where an item will be skipped and you continue | |
* or break a loop. | |
*/ | |
foreach( $fields as $field ) | |
{ | |
if( !isset($field) ) | |
{ | |
continue; | |
} | |
else | |
{ | |
// do some things with $field | |
} | |
} | |
OR | |
foreach( $fields as $field ) | |
{ | |
if( isset($field) ) | |
{ | |
// do some things with $field | |
} | |
} | |
/** | |
* Proper: | |
* - easier to read | |
* - less indentation | |
* - short circuit is explicit enough for any programmer to understand | |
*/ | |
foreach( $fields as $field ) | |
{ | |
if( !isset($field) ) continue; | |
// do some things with $field | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment