Home > Software engineering >  Can someone explain me this loop in php? I can't understand why $a gets value 20
Can someone explain me this loop in php? I can't understand why $a gets value 20

Time:06-02

translation of the exercise: There is a code snippet in PHP. After the loop is over, the variable a gets value

CodePudding user response:

$a starts out as 0 and $i as 10.

The code inside the while loop will run as long as the expression inside the () is true. In PHP, any number that isn't 0 is considered true.

Each time the loop runs (or as we say, each "iteration of the loop", two things happen:

  1. $a is set to $a 2. In other words, $a is now whatever it was before, plus 2.

  2. $i is "decremented" by 1. In other words, $i is now whatever it was before, minus 1.

Here are the values of each variable at the end of each iteration:

Iteration Value of $a Value of $i
1 0 2 = 2 10 - 1 = 9
2 2 2 = 4 9 - 1 = 8
3 4 2 = 6 8 - 1 = 7
4 6 2 = 8 7 - 1 = 6
5 8 2 = 10 6 - 1 = 5
6 10 2 = 12 5 - 1 = 4
7 12 2 = 14 4 - 1 = 3
8 14 2 = 16 3 - 1 = 2
9 16 2 = 18 2 - 1 = 1
10 18 2 = 20 1 - 1 = 0

Since $i is now 0, the expression in the () is considered false, so the loop stops, and the value of $a is 20.

  • Related