|
Posted by ZeldorBlat on 05/15/07 14:32
On May 15, 10:21 am, Darko <darko.maksimo...@gmail.com> wrote:
> On May 15, 4:07 pm, harvey <harvey....@blueyonzders.com> wrote:
>
> > What is the easiest way to get both the last item name and last item
> > value from an associative array?
>
> > I can get the value with array_pop() but can't see anything similar
> > for the item's name.
>
> > Thanks
>
> Associative arrays are usually stored in memory as binary trees,
> therefore there is no such thing as "the last element". If you rethink
> it, it's logical, since if you have an array that has integer indices,
> than you _can_ have the "last element" (the element with the largest
> index), but if you have an associative array, what is "the last"
> element? As far as the array is concerned, they are all equal and you
> retrieve them by their key. If what you think is the last element is
> the element you put the last into the array, then it's something you
> have to take care of while inserting them. If you think of the element
> that has the biggest index lexically than you have to find the way to
> sort them.
>
> The one thing that you could do that crosses my mind however, which is
> a stupid thing, I must admit, and which looks like something you would
> get the results you are looking for, would be to do ob_start(), then
> print_r(), then ob_get_contents(), then ob_end_clean(), and parse the
> output. But as I said, it doesn't look too nice to me.
Even arrays with associative indexes have an ordering to them. Try
the following:
$a = array('foo' => 'bar', 'baz' => 'bop');
print_r($a);
$b = array('baz' => 'bop', 'foo' => 'bar');
print_r($b);
And they come out in the same order as they were specified. In fact,
the same holds true for numerically indexed arrays -- the last element
isn't necessarily the one with the largest index:
$a = array(2 => 'bar', 1 => 'foo');
print_r($a);
To answer the OP's question, you can do something like this:
$a = array('foo' => 'bar', 'baz' => 'bop');
end($a); //set the pointer to the end of the array
$lastKey = key($a);
$lastValue = current($a);
[Back to original message]
|