Understand loops

Learn how loops iterate over arrays and objects

Loops are just iterators, understanding how they work is important!

In every programming language you will eventually have to deal with loops, understanding how they work behind the scene can be really helpful, specially when dealing with large and complex applications, obviously performance is a key factor in large applications and this article will introduce you to the concept of loops and will cover all the basics.

Iterators are nothing more then a sequence generator.

What is a sequence?

A sequence is an ordered list of values; values can be repeated in a list multiple times and the order does not need to be sorted.

The most basic type of sequence in programming is the array.

Array elements can be any value and they can be positioned in any order, but once they are set, the array has a defined order.

For instance in PHP we normally loop through an array with the foreach construct, so each loop will have the next item in a sequence until we run out of items.

Note: foreach loop can only iterate over arrays and objects; if you try to iterate over a variable with different data type, you will get an error.

E.g:

$shopItem = array('banana', 'apple', 'orange', 'blueberry');

foreach($shopItem as $item) {
    echo $item . "\n";                      
}

The other loop that you are probably familiar with or at least have heard about it, it's the for loop. The for loop is the most complex loop in PHP, they behave like their C counterpart.

E.g:

for( $i = 0; $i < count( $shopItem ); $i++) {
    echo $shopItem[$i] . "\n";
}

Without even realising, each time you build a loop like this one you are building an iterator, which is just an abstraction of this for loop.

Process:

$i = 0 is a rewind() method.

$i < count($shopItem) is a valid() method.

$i++ are the same as the next() method.

echo $item; is the code in the loop.

The iterator interface

interface iterator {
    public function rewind();
    public function valid();
    public function next();
    public function key();
    public function current();
}

So let’s see how we would write the for loop with the iterator methods.

for( $it->rewind(); $it->valid(); $it->next() ) {
    $key = $it->key();
    $value = $it->current();
}

In reality thats exactly how the for loop does behind the scenes anyway. The difference between the iteration in the for and foreach loop is that the foreach loop provides the key and value automatically.

E.g:

foreach($shopItem as $key => $value) {
    echo "Key: " . $key . "\n";
    echo "Value: " . $value . "\n"; 
}

Note: When using foreach arrays and iterators and interchangeable. Let’s build the for loop but as an iterator instead, just to clarify.

class ForLoopIterator implements Iterator {

   Protected $array = array();
   Protected $i = 0;

   public function __construct( $givenArray ) {
      $this->array = $givenArray;
   }

   public function rewind() {
      $this->i = 0;
   }

   public function valid() {
      return $this->i < count($this->array);
   }

   public function next() {
      $this->i++;
   }

   public function key() {
      return $this->i;
   }

   public function current() {
      return $this->array[$this->i];
   }

}

The first thing we did was to implement the iterator interface, which provided us with the 5 methods we needed. Also provides some magic that enables us to use objects in foreach statements. 

One of the benefits of using iterator is that you can save significant amount of memory by only generating values that are needed when they are needed.

Another benefit of an iterator is that we can implement methods to provide additional functionality.

Comments

blog comments powered by Disqus