View Single Post
  #4  
Old 04-11-2017, 10:11 PM
ewe ewe is offline
Member
 
Join Date: Mar 2017
Posts: 8
Gender: Female
Credits: 1,891
ewe is on a distinguished road
Default

Oh, I'd be more than happy to explain how a for loop works! I think it's the easiest way to explain what a loop is to someone because they're pretty straightforward.

Let's say Bart Simpson had a brilliant idea to make school a little more exciting one day but Mrs. Crab Apple decided to ruin all the fun like always. In her characteristic punishment (because she's so creative) she orders Bart to write a correction for his behavior 100 times on the chalk board.

If Bart could enter the 21st century and use a computer instead of a chalkboard he could use a for loop and be done in a matter of minuets.

This example is very important and not just an excuse for me to include a picture with the word sheep. I swear.

A for loop is usually used to go through a set of actions an exact number of times. The syntax is similar to if(conditions) {do stuff;} so I'll explain what actually happens inside the parenthesis.

for ($i = 1;
Here you create a variable that acts as a counter. Usually it is set to 1 but you can actually start at any integer. You can reuse $i in different loops but if you have a for loop inside a for loop you need to use different counters. (I tend to use $i and $j)
$i <= $numberOfTimes;
Here you compare your counter to your target variable. You can use an integer like 42 or you can use a $variable. You shouldn't ever say $i = $target; because it is theoretically possible you could miss your target and end up with an infinite loop. If you use <= (or >=) you'll include the target value. If you want something to happen 10 times you can either set $i = 1 and $i <= 10 or you could set $i = 0 and $i < 10.
$i++) {
This is just shorthand for $i = $i + 1); If you wanted a for loop that counts down instead just use $i--!Note there is no ; here! I'm not sure why but all of the languages I've seen (like 3) use this format
&nbsp;&nbsp;&nbsp;stuff happens over and over;
}

  Spoiler: If you've taken Calculus it's a bit like summation notation 


x = 1 below the Sigma is like $i = 0, the number above the the sigma is the target value
Actually this site gives a decent explanation if you need a refresher or would just like another different explanation.
Reply With Quote