PHP PHP Arrays and Control Structures PHP Loops While Listing Array Values

Hey There
Hey There
3,086 Points

Why does this loop run twice?

I thought this loop should run only once since the first round $count++ makes the value to become 1 which is <2. But the second time $count++ becomes 2 which is not <2 anymore. But why are there 2 results in the output?

$learn = array('Conditionals','Arrays','Loops'); $learn[] = 'Build something awesome!'; array_push($learn,'Functions','Forms','Objects'); array_unshift($learn,'HTML','CSS'); asort($learn);

$count = 0; while ((list($key, $val) = each($learn)) && $count++ <2) { echo "$key => $val\n"; }

OUTPUT:

3 => Arrays
5 => Build something awesome!

1 Answer

$count++ < 2

This checks that the value of $count is less than 2 (it is because it is 0) and then the ++ increases it by one. Then on the second loop, the value of $count is 1, so it is less than 2 and the ++ increases it by one.

This is why the loop executes twice. You can fix this either by changing the test to $count < 1 OR ++$count < 2. The second one here increments $count BEFORE doing the test. However, the first fix is clearer.