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

Matthew Root
Matthew Root
5,392 Points

What is the difference between a While loop and a Foreach loop?

I know these to loops are very similar but can anyone give me specifics on what is the difference between a While loop and a Foreach loop? What would be a specific situation that I would want to use a while loop instead of a foreach and vice versa? Thanks!

1 Answer

Jaanus Alnek
Jaanus Alnek
1,685 Points

A while loop executes orders until a certain condition is met(condition has to be non-zero/null valued for it to execute). A regular for loop provides a variable and a way to count many times it has executed orders and still executes orders while a condition is true. Foreach however takes an array of objects as input and lets you execute commands while it goes through the array giving you access to each object in turn.