Simply
$array = array("a" => array(1, 2, 3),"b" => array(4, 5, 6));
end($array);
echo key($array);
Output
b
Sandbox
the call to end
puts the internal array pointer at the end of the array, then key gets the key
of the current position (which is now the last item in the array).
To reset the array pointer just use:
reset($array); //moves pointer to the start
You cant do it in one line, because end returns the array element at the end
and key
needs the array as it's argument. It's a bit "Weird" because end
moves the internal array pointer, which you don't really see.
Update
One way I just thought of that is one line, is to use array reverse and key:
echo key(array_reverse($array));
Basically when you do array_reverse
it flips the order around and returns the reversed array. We can then use this array as the argument for key()
, which gets the (current) first key of our now backwards array, or the last key of the original array(sort of a double negative).
Output
b
Sandbox
Enjoy!