![]() |
|
#1
|
|||
|
|||
![]()
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. ![]() ![]() 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 stuff happens over and over; } ![]() |
![]() |
Thread Tools | |
Display Modes | |
|
|
What's New? |
What's Hot? |
What's Popular? |