This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
for loops are the most complex loops in PHP because they use 3 expressions instead of just one. But complex doesn't need to mean difficult. Sometimes having something more complex in one place is actually easier to read than looking for all the simple pieces.
Documentation
for loops are the most complex loops in PHP because the contain three expressions. The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions separated by commas.
Additional Examples
Single line for loop
for($year = date('Y')-100; ++$year <= date('Y'); print $year."<br />");
Looping through Letters
You can also loop through letters (Very convenient when working with excel columns.)
for ($letter = 'A'; $letter != 'AA'; $letter++) {
echo $letter."<br />";
}
Take note that you can't use $letter < 'AA'. It only works with !=. If you wanted to use <= you would need to use the actual ordinal value of the characters
for ($letter = ord("A"); $letter <= ord("Z"); $letter++)
{
echo chr($letter) . ", ";
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up