Here come my benchmark, and
return key(array_slice($array, -1));
is the my best answer for a polyfill.
<?php
function array_key_last_1(array $array) {
return key(array_slice($array, -1));
}
function array_key_last_2(array $array) {
return key(array_slice($array, -1, 1, true));
}
function array_key_last_3(array $array) {
return key(array_reverse($array));
}
function array_key_last_4(array $array) {
return array_keys($array)[count($array) - 1] ?? null;
}
function array_key_last_5(array $array) {
return array_keys($array)[count($array) - 1] ?? null;
}
function array_key_last_6(array $array) {
$copy = array_keys($array);
return end($copy);
}
$result = array();
$array = range(0, 1000000);
for($i=1; $i < 7;$i++) {
$callback = 'array_key_last_' . $i;
$before = microtime(true);
call_user_func_array($callback, array($array));
$after = microtime(true);
$time = ($after-$before);
$result[$callback] = $time;
}
asort($result);
foreach ($result as $key => $value) {
echo '[' . $key . ']' . $value . " sec" . PHP_EOL;
}