Home Logic Ubuntu (Linux) Blog PHP Fiddle

PHP: forLoop

  What is a loop?

A loop is a block of code that executes more than once. Each instance of code execution is call an iteration



  How many iterations?

Some times we know how many times we want code to run, and sometimes we do not. There are different types of loops we can use. Which loop you decide to use will depend on the situation and your personal preference.



  Syntax


// for loop syntax
for (initialize counter/index; condition; increment counter;) {
  code to be executed;
}
        

// for loop example
for ($i = 0; $i < 5; $i++) {
   echo $i;
}
        
Try running the appove code: PHP Fiddle

In our for loop example:

Counter: $i is our counter
Init: At first iteration, $i equals 0
Condition: The code will continue to executed as long as $i is less than 5
Increment ($i++): At the end of each iteration, 1 is added to the counter.



  Loops && Arrays

Loops are commonly used with arrays. The PHP for loop works great with indexed arrays!

We can have our counter equal to our array index. We will initialize our counter ($i) at 0. Our loop will continue to execute, as long as our counter is less than the number of elements in our array

We can use the PHP predefined function count() to tell us how many elements are in an array.



// declare beverage array
$beverages = array("Red Bull", "coffee", "tea", "pop");

// number of elements in $beverages
$count = count($beverages);

// for loop
for ($i = 0; $i < $count; $i++) {
    echo "$beverages[$i] | ";
}
        
Try running the appove code: PHP Fiddle

Output: