Reputation: 612
Why doesn't the double equals work in a PHP for loop? The following works:
$cnt = 5;
for ($z = 0; $z <= $cnt; $z++) {
echo $z."!<br />";
}
But why doesn't this work?
$cnt = 5;
for ($z = 0; $z == $cnt; $z++) {
echo $z."!<br />";
}
Upvotes: 1
Views: 4035
Reputation: 234795
The loop executes only if the condition evaluates to true
. At the first iteration, $z == $cnt
is false
, so the loop never executes.
A common loop strategy is to use a sentinel value:
$cnt = 5;
$stop = $cnt + 1;
for ($z = 0; $z != $stop; $z++) {
. . .
}
Note that the comparison is negative (!=
or !==
). Using a sentinel is usually unnecessary for numerical loop variables (I wouldn't recommend it for your posted code), but is useful for other situations (e.g., when $stop
represents null
, an illegal value, etc.). It's particularly helpful when the loop variable changes in a pattern that is not easy to characterize succinctly.
Upvotes: 3
Reputation: 780724
The syntax of for
is:
for (<init>; <condition>; <increment>)
The loop tests <condition>
before each iteration. If it's true
, it executes that iteration; if it's false
, the loop terminates.
In your case, since $z == $cnt
is false
before the first iteration, the loop terminates immediately.
To do what you want, invert the test. You also need to bump the end value up by one, since the original version used <=
, not <
. Note that in both cases, the loop executes $cnt+1
times, because you start from 0.
for ($z = 0; $z != $cnt+1; $z++)
Upvotes: 1
Reputation: 1335
A for loop works by looping until a condition is made false. In the first example the loop will execute until z = 5 after that z will not longer be less than or equal to cnt (z starts at 0 and increments through each loop). In the second example you have $z == $cnt as your condition, and since z = 0 and cnt = 5 the loop will stop automatically because the condition is made false. You can use not equals instead like following:
$cnt = 6;
for ($z = 0; $z != $cnt; $z++) {
echo $z."!<br />";
}
Upvotes: 1
Reputation: 169
Let us look at this from the computer's perspective:
If I am a computer this is what you told me to do:
Trouble is, 5 does not equal 0 and never will, so the loop will simply be skipped. If you had $cnt = $z+1 inside the loop this would be an infinite loop.
So, you see, == works just fine, it simply doesn't do what you think it should do.
Hope this helps!
Upvotes: 1
Reputation: 8606
because on the first iteration $z != $cnt
, so the loop stops immediately.
Upvotes: 1