NYCPHP Meetup

NYPHP.org

[nycphp-talk] Accessing First Element of Array

Michael B Allen ioplex at gmail.com
Sun Aug 26 21:42:18 EDT 2007


On 8/26/07, Dell Sala <dell at sala.ca> wrote:
> On Aug 26, 2007, at 9:08 PM, Michael B Allen wrote:
>
> > On 8/26/07, Jon Baer <jonbaer at jonbaer.com> wrote:
> >> Is it anything that $array[0] would not be able to get access to?
> >
> > Nope. The 0 element is not necessarily first. Consider the
> > following example:
> >
> > $array = array();
> > $array['first'] = 'foo';
> > $array[] = 'bar';
>
>
> How about this:
>
> $values = array_values($array);
> $first = $values[0];

Yes, that would work. But building a new array is potentially very
expensive. So far the following is the best I can think of:

function _array_first($a, $want_key=FALSE) {
    foreach ($a as $key => $elem)
        return $want_key ? $key : $elem;
    return FALSE;
}

Mike



More information about the talk mailing list