Created
January 4, 2016 06:29
-
-
Save shadowhand/844f5005d51c7f5c75c2 to your computer and use it in GitHub Desktop.
Why is https://wiki.php.net/rfc/array_key_first_last_index necessary?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function array_key_first(array $arr) | |
{ | |
reset($arr); | |
return key($arr); | |
} | |
function array_key_last(array $arr) | |
{ | |
end($arr); | |
return key($arr); | |
} |
maybe
function array_key_first(array $xss)
{
return [] === $xss
? null
: array_keys(array_slice($xss, 0, 1, true))[0];
}
function array_key_last(array $xss)
{
return [] === $xss
? null
: array_keys(array_slice($xss, -1, 1, true))[0];
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reset() modifies the array, forcing a copy to be made. For large arrays, this can be slow and consume memory. A significantly more performant (in PHP 7 only) polyfill for array_key_first would be:
array_key_last() would still suffer from all the issues presented in the RFC.