NYCPHP Meetup

[nycphp-talk] Accessing First Element of Array

Michael B Allen ioplex at gmail.com
Mon Aug 27 12:54:47 EDT 2007


On 8/27/07, Ken Downs <ken at secdat.com> wrote:
> "Michael B Allen" <ioplex at gmail.com> wrote:
>
> > >
>  > >
>  > > Um, you could, uh, write a function called array_first() that does the
>  > > reset() and then calls each()? Then maybe even calls reset() again?
> Then
>  > > you could, like, maybe, only use this function and not make arbitrary
> use of
>  > > each() and reset() in your code?
>  >
>  > I guess you missed my earlier post. This is what I'm using right now:
>  >
>  > function _array_first($a, $want_key=FALSE) {
>  > foreach ($a as $key => $elem)
>  > return $want_key ? $key : $elem;
>  > return FALSE;
>  > }
>  >
>  > > And btw, when you write that function, pass the array by reference, not
> by
>  > > value.
>
> No, I caught your post, it's just that an experienced PHP programmer would
> never write the function you wrote to do what you're doing.  They'd use
> each().
>
> Hint: read the manual to find find out why I told you to pass by reference,
> read the manual to find out what foreach does internally.

Hi Ken,

I appreciate your help but I don't have a lot of time for games. After
reading the manual for each() I see nothing to indicate that using
each() w/ reset() would be superior to the foreach() method I've been
using. The each() function already accepts references and AFAIK
runtime pass-by-reference is being deprecated anyway. Also, even if
there is something that would preserve the state of the array cursor,
that would suggest that a copy of the array would be made which could
be potentially very slow.

I'd very willing to accept direction as I spend a lot more time
writing C than I do PHP but I have to admit sometimes I have trouble
reading between the lines. If you still care to help please spell it
out for me why each() w/ reset() is superior to the foreach() method
I've been using.

Thanks,
Mike



More information about the talk mailing list