Skip to content

Instantly share code, notes, and snippets.

@icambridge
Last active December 26, 2015 01:29
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 icambridge/7071555 to your computer and use it in GitHub Desktop.
Save icambridge/7071555 to your computer and use it in GitHub Desktop.
A simple break down of for loops

Understanding for loops

the basic syntax of a for loop goes

for ($var = 0; $var < 10; $var++) {
    // do stuff
}

iterlation To understand how the for loop works you need to understand that the code with the () is broken down into 3 steps seperated by semi colons.

Step 1

$var = 0;

The first step of the loop is generally where you create variables that are to be used with in the loop, the most common usage is to set the counter to the starting point. This is executed once at the start of the loop and never executed again.

Step 2

$var < 10

The second step is the boolean return step, where the loop sees if it's to continue. if it's to continue the return value of the second step is to be true. This code is executed at the start of every loop, including the first iteration. This means if you have a function call within that step it will be called on every iteration.

Step 3

$var++

The third step is generally where you increment the counter. This step is executed at the start of every iteration.

Code block

The code within the for loop is executed as it was on the same execution statement(line) of execution this is why when you do $i++ the increment is on the next step.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment