note 125319 added to function.array-key-last
| From: | donaldinou at gmail dot com | Date: | Wed, 02 Sep 2020 12:58:03 +0000 |
| Subject: | note 125319 added to function.array-key-last | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-215057@lists.php.net to get a copy of this message | ||
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) {
// assert(!empty($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;
}
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.167.36 (proxied: 90.63.248.203)
----
Manual Page -- http://php.net/manual/en/function.array-key-last.php
Edit -- https://master.php.net/note/edit/125319
Del: integrated -- https://master.php.net/note/delete/125319/integrated
Del: useless -- https://master.php.net/note/delete/125319/useless
Del: bad code -- https://master.php.net/note/delete/125319/bad+code
Del: spam -- https://master.php.net/note/delete/125319/spam
Del: non-english -- https://master.php.net/note/delete/125319/non-english
Del: in docs -- https://master.php.net/note/delete/125319/in+docs
Del: other reasons-- https://master.php.net/note/delete/125319
Reject -- https://master.php.net/note/reject/125319
Search -- https://master.php.net/manage/user-notes.php