On 07/14/2012 10:29 AM, Rasmus Lerdorf wrote:
> On 07/14/2012 10:13 AM, Anthony Ferrara wrote:
>> Gustavo,
>>
>> Why is the last key special? Why not a function to get the first or the
>>> penultimate key?
>>>
>>
>> How would such a function look?
>
> I think the function would look just like the function we have for doing
> this.
>
> key(array_slice($arr,-2));
>
> And no, this has no side-effect of changing the array pointer in $arr,
> of course.
>
> And array_last_key() is identical to array_slice($arr,-1) is it not?
>
> The only thing array_last_key() saves is a single function call to
> key(). That doesn't seem worth it to me.
Ok, with the slight modification that for numeric keys we would want to
preserve the keys.
function array_last_key($arr) {
return key(array_slice($arr,-1,null,true));
}
And despite what the docs say, the array pointer is not changed.
Test:
$a = [ 'first'=>1, 'second'=>2, 'third'=>3,
'last'=>4 ];
next($a);
next($a);
echo key($a);
echo array_last_key($a);
echo key($a);
This outputs:
third
last
third
-Rasmus