+ 3
Can someone explain to me the step by step on how for loop works
2 Answers
+ 6
for (int A = 0; A < 10; A++) {
//code
}
When the first iteration of the loop starts, the code in the first section runs. In this case, it creates a variable A and gives it the value, 0.
Next, if the condition in the second section is true, the code runs. You can use A in here.
Now, it tests the condition again, just like in a while loop, and if it is true, it runs the code in the third section and then runs the loop again. A still exists at this point.
Once the loop finally ends because the condition is false, A gets deleted.
Now, that is how it works, but why not just use a while loop?
A for loop is specifically designed for counting a certain number of iterations. The main benefit is being able to declare a variable that will stay for every iteration but get deleted afterwards. It is also useful because it forces you to remember to increment the variable you are using to count.
+ 3
<?php
// We have 7 indices start from 0 in the $weekdays array.
$weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
// loop through those indices by incrementing by 1, until we get 6.
// Now pass the $i as index in weekdays array.
for ($i=0; $i <= 6; $i++) {
echo $weekdays[$i]."<br>";
// Outputs:
// Monday
// Tuesday
// Wednesday
// Thursday
// Friday
// Saturday
// Sunday
// to get the same result without looping.
// we would do it like:
/*
echo $weekdays[0]."<br>";
echo $weekdays[1]."<br>";
echo $weekdays[2]."<br>";
echo $weekdays[3]."<br>";
echo $weekdays[4]."<br>";
echo $weekdays[5]."<br>";
echo $weekdays[6]."<br>";
*/
/* So now you can see how looping can be useful.
// foreach can achieve the same too: foreach ($variable as $key => $value) {
# code...
}
*/
}
// I hope it helps