Web Development

Using Control Structures and Foreach Loops in PHP

PHP Foreach Loops

The type of control structure we’re going to discuss is the ‘foreach’ loop.� The ‘foreach’ loop allows you to iterate over each value of an array.� The ‘foreach’ loop has two syntaxes, one for arrays you might have initialized, and one more specifically for associated arrays which you might have initialized.� Here are the syntaxes for both:

}

The above “foreach” loop says the following:� “foreach element (person) in the array (people), print the element (person’s name)”.� The example above will have the following output:

“Darren
Jeff
Joseph
Scott
David
Alex”

Of course you don’t just have to print out each value in the array.� There are endless possibilities of what you can do with each value in the array.� I just think that printing each element is the easiest and therefore will show you the most clearly how to use a “foreach” loop.� Let’s do the same thing with the associated array syntax:

}

The example above will have the following output:

“person1 – Darren
person2 – Jeff
person3 – Joseph
person4 – Scott
person5 – David
person6 – Alex”

That’s about it for the “foreach” loop.� So you might ask why is the “foreach” loop called a control structure.� Well that’s because PHP will run the block of code as many times as there are elements in the array.� It will execute the block, move back up, and execute again until all the elements are dealt with.

That’s about it for the “foreach” loop.� Hopefully those of you reading the tutorials aren’t finding these hard or complicated to understand.� The lessons at this point might seem a little like they’re all over the place, but by the time the main lessons are complete, I’ll demonstrate putting all these lessons together to create simple programs.� For those of you that really want to learn, expect homework after the main lessons are done.� The homework won’t be at all complicated or tricky, but it will help you understand some of PHP’s features better.

About the author

Written by Darren W..

Darren Hedlund is a freelance Web developer, writer, and data analyst. Darren has a degree in Computer Information Science and has spent the last 15 years developing application and environments from hand held, windows, web, virtual science, gaming, artificial intelligence and graphics design.

Darren's coding knowledge ranges from C+, Visual Basic, .NET, PHP, JSP, REXX, KIXX, and many others. His graphical and environmental knowledge stems in Macromedia Flash, 3D studio Max, Curious Labs Poser, Adobe Photoshop, and many others. Darren works in many platforms ranging from database, visual design, and, system development.

If you found this post useful you may also want to check these out:

  1. Control Structures and While Loops
  2. Basic Control Structures in PHP
  3. Creating a Drop Down Selection with an Array
  4. Perl Sorting
  5. Using Arrays in JavaScripts
  6. Creating a PHP Looping Statement