NYCPHP Meetup

NYPHP.org

[nycphp-talk] Accessing First Element of Array

Michael B Allen ioplex at gmail.com
Sun Aug 26 22:37:18 EDT 2007


On 8/26/07, Ken Downs <ken at secdat.com> wrote:
> "Michael B Allen" <ioplex at gmail.com> wrote:
>
>  > On 8/26/07, Ken Downs <ken at secdat.com> wrote:
>  > > "Michael B Allen" <ioplex at gmail.com> wrote:
>  > >
>  > > > On 8/26/07, Ken Downs <ken at secdat.com> wrote:
>  > > > > look at "each", it is a (mostly deprecate) form of array iteration.
> The
>  > > > > sample code in the PHP manual will show exactly what you are
> looking
>  > > for.
>  > > >
>  > > > But again that modifies the array (it advances the cursor).
>  > >
>  > > Not really. It does not modify the keys or the values. The cursor is a
>  > > variable used to determine which key and value is returned on the next
> call
>  > > to each().
>  > >
>  > > If you absolutely must have the state exactly the same before and
> after,
>  > > then add a call to reset() to your code, it is mentioned in that page
> in the
>  > > manual.
>  >
>  > Again, reset changes the array. The cursor is part of the array's
>  > state such that calling it at an arbtrary location within your code
>  > could change the logic of the application.
>
>
> 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.

With the above function I don't think it is necessary to pass by
reference because the array state is not modified and the array is not
returned from the function so it should not copy (I'm not positive
about this - I would be curious to know if someone had the definitive
answer on this scenario).

Mike



More information about the talk mailing list