View Single Post

  #9 (permalink)  
Old 05-08-2008
chander@otg-nc.com
 
Posts: n/a
Default Re: For loop question?

On May 8, 4:07*pm, Ivan Marsh <ivanma...@yahoo.com> wrote:
> On Thu, 08 May 2008 22:05:48 +0200, Iván Sánchez Ortega wrote:
> > Ivan Marsh wrote:

>
> >>> When iterating through arrays, *always* use foreach().

>
> >> Isn't foreach simply creating a for loop based on the size of the array?

>
> > No.

>
> Can you expand on that?
>
> --
> "Remain calm, we're here to protect you!"


Foreach loops work by iterating over the keys of an array, and are
universal in that they work with both simple arrays (sequential
integer keys) and associative arrays (those where the keys are not
strings).

Furthermore, the standard form of foreach retrieves the associated
value when it retrieves they key, hence making the iteration over the
values in an array a bit faster (since no additional lookup is
required).

Lastly, a foreach loop can operate on a function that returns an array
(as opposed to a variable that contains an array) in a fairly
straightforward manner, whereas a for loop requires that the array be
assigned to a variable beforehand.

--
Chander Ganesan
Open Technology Group, Inc.
One Copley Parkway, Suite 210
Morrisville, NC 27560
919-463-0999/877-258-8987
http://www.otg-nc.com
Ask me about Expert on-site and public enrollment PHP Training
delivered worldwide.
Reply With Quote