Using Control Structures and Foreach Loops in PHP
By Darren W. Hedlund2005-06-21
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:
foreach (array_expression as $value) { do something with $value } |
|
As you can see, we've declared an array called $people which store the names of a few people.� While you can get access each element using $people[0 to 5] (as we discussed in our array lesson), if you didn't know how big the array was, you'd never know how far to go.� There is a combination of a loop and a function you could use, but for now, this is the SIMPLEST way to iterate through an entire array.� Let's use the above array and the above "foreach" loop syntax to write out a simple example:
|
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.
Tutorial pages:
|
|
|||||||||
You might also want to check these out:
|
Link to This Tutorial Page!

