RE: Newb question about getting keys/values from a single array element
| From: | Daevid Vincent | Date: | Fri, 09 Oct 2009 19:46:44 +0000 |
| Subject: | RE: Newb question about getting keys/values from a single array element | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-298822@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Shawn McKenzie [mailto:nospam@mckenzies.net]
> Sent: Friday, October 09, 2009 5:32 AM
> To: Daevid Vincent
> Cc: php-general@lists.php.net
> Subject: Re: Newb question about getting keys/values from a
> single array element
>
> Daevid Vincent wrote:
> > I feel like a total newb asking this, but I'm just having a
> brain fart or
> > something...
> >
> > I'm writing a page where I can either get back a list of items:
> >
> > Array {
> > [1233] => "apple",
> > [6342] => "apricot",
> > [2345] => "banana",
> > ...
> > }
> >
> > where the user then refines it by choosing one single item
> and a single
> > element array is returned like this:
> >
> > Array {
> > [8575] => "peach",
> > }
> >
> > How can I get this $item so I can print it like so:
> >
> > echo "The ID is $id and the name is $name";
> >
> > Normally with an array of items, I do a:
> >
> > foreach ($item as $id => $name) echo...
> >
> > But that seems overkill for this scenario.
> >
> > The rub is that I don't know the "id", so I can't use
> $item[0], and I also
> > don't have something like $item['name'] to use either.
> >
> > There's got to be an easy way to extract those.
> >
> > list($id, $name) = $operator;
> >
> > Felt like it would work for a minute (wishful thinking).
> >
> >
> > (I'm too embarrased to even sign my name on this one)
> >
>
> $a = array(8575 => 'peach');
>
> $key = key($a);
> $value = current($a);
BRILLIANT! That's EXACTLY what I was looking for!