Skip to content

Instantly share code, notes, and snippets.

@jrtashjian
Created September 14, 2011 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrtashjian/1218093 to your computer and use it in GitHub Desktop.
Save jrtashjian/1218093 to your computer and use it in GitHub Desktop.
short-circuiting loops
<?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