Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.