headphono.us

Avatar

Pras Sarkar blogs about web technology, music, social networks, digital identities and other random things.

Having fun with for loops

I love for loops. I use them in ways they probably shouldn’t be used for. Here are some few fun ways of using for loops with the caveat that not all these should be used since they are unorthodox and may not be easily readable to others in your team.

For loops for concise conditional logic

Have you ever come across a pattern where you need to set a new variable, check it against another limit variable and then depending on a condition (limit variable is greater/lesser than your new variable), update it accordingly?

Here’s an example:

$page = $_GET['page'];
if ( $page < 0 ) {
  $page = 1; // pages can't be lower than 1
}

While the above snippet is completely readable (and somewhat contrived), there’s a more concise way to use for loops to achieve the same result:

for( $page = $_GET['page']; $page < 1; $page = 1 );

The reason this works is because the for loop has three useful parts: initialization, conditional and mutator. If you ever come across a pattern in code that requires a combination of the three, chances are you can use a for loop. The above would be evaluated as follows:

  1. $page gets initialized
  2. the conditional is evaluated
  3. if found true, it runs through the for loop execution (which is empty)
  4. the mutation section sets $page to 1
  5. it evaluates the conditional again and finds it to be false and exits out of the for loop

For loops for short circuit search

There are times when you need to find the index of an element in an array provided it matches some condition. For example, let’s say you have an array of breadcrumb nodes, and you need to walk the array to find out at which index the current page matches. If you have lots of pages in the array, you’d probably want to walk the array as far as your match. Using a while, it looks like:

$arr = array(
     '/home/', 
     '/home/products/',
     '/home/products/1', 
     '/home/products/2' );
$this_page = '/home/products/1';
$i = 0;
 
while( $arr[$i] != $this_page ) {
  $i++;
}
// $i = 2

Now let’s try that with a for loop:

for( $i = 0; $arr[$i] != $this_page; $i++ );

What else can you do with a for loop?

You can implement reverse sort pretty concisely:

function swap( &$a, &$b ) {
   $temp = $a;
   $a = $b;
   $b = $temp;
}
 
function reverse( &$arr ) {
   for($i=0,$j=count($arr)-1;
        $j>$i;
        swap($arr[$i++],$arr[$j--])
    );
}
 
$arr = array( 1, 2, 3, 4, 5 );
reverse( $arr );
 
// $arr = array( 5, 4, 3, 2, 1 );

I hope this helps you find more unorthodox uses of the useful for loop, and realize that it’s not just to iterate over a collection/array. If you already use for loops in a clever way, leave a comment and share with others.

Tags

Related Posts

2 Comments, Comment or Ping

  1. That first one is clever, but I would say it’s more a job for the max() function. Using max would also clear up some ambiguity: the comment says “pages can’t be less than 1″ but the code only changes negative numbers to 1, leaving 0 alone.

    As a Lisp hacker I don’t believe in loops anyway. (just kidding)

  2. Good catch Dan. I fixed the typo in the first example.

Reply to “Having fun with for loops”

My Lifestream

My shenanigans around the web