Avoiding Counters In Loops

When writing code I try to keep things clean but one thing has always bothered me, using $i (or something similar) as a counter, incrementing it on each step. Here’s an alternative approach which you can use with arrays to get around those pesky counters.

The Old Way

$navigation = array( 'Home', 'Contact', 'About' );

$i = 0;
foreach( $navigation as $item ) {
    $current = ( $i == 0 ) ? 'current' : '';
    echo '<a class="' . $current . '" href="#">' . $item . '</a>';
    $i++;
}

This works fine but I just don’t like it. It just seems like there are two unneeded lines but more importantly, this lends itself to making coding errors. The current class depends on you remembering to set $i = 0. If you forget to do so the value of $i may come from somewhere else – a previous loop for example.

If you have more complex rules set up to detect the current class you may not even notice the error. If the value of $i is set in a prior loop you may simply see on offset which you may or may not actually notice.

The Better Way

$navigation = array( 'Home', 'Contact', 'About' );

foreach( $item = current( $navigation ) ) {
    $current = ( key( $navigation ) == 0 ) ? 'current' : '';
    echo '<a class="' . $current . '" href="#">' . $item . '</a>';
    next( $item );
}

While not much shorter this is much better because the current value is now inherently contained inside the actual array keys. If something doesn’t work here you can be pretty sure the problem is in the loop and if it seems to work, you can be pretty sure it actually does.

If you haven’t seen this before take a look at the current() function on the PHP codex, it has all the similar functions listed below for moving pointers and such, very handy!

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated. Thanks for dropping by!