Home > Enterprise >  Unexpected value after for-loop in PHP vs Python
Unexpected value after for-loop in PHP vs Python

Time:01-02

Why does last value in for-loop differ in PHP vs Python? I am checking the value after the for loop. The value is not 7 that I would expect as in Python 3.9.7. In PHP 8.0, the last value in the for-loop is 8 instead. This an an abstracted example from my implementation, since I am checking the value after the for-loop because I have conditional breaks.

for ($i = 1; $i <= 8;   $i) { echo "i: $i\n"; } echo "end $i\n";
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
end 8

Python

>>> for n in range(1,8):
...     print(n)
... 
1
2
3
4
5
6
7
>>> print(n)
7

CodePudding user response:

$i increments, condition met / not met ...continue loop / continue execution. So generally speaking, the incrementation happens before the comparison takes place, in order to know the value of the current iteration, which the exit condition is being compared to. This is only logical.

And you've ported the Python code wrongfully ...therefore comparing apples to pears.

foreach (range(1, 8) as $number) {
    echo $number;
}
  • Related