Skip to content

Instantly share code, notes, and snippets.

@shadowhand
Created January 4, 2016 06:29
Show Gist options
  • Save shadowhand/844f5005d51c7f5c75c2 to your computer and use it in GitHub Desktop.
Save shadowhand/844f5005d51c7f5c75c2 to your computer and use it in GitHub Desktop.
<?php
function array_key_first(array $arr)
{
reset($arr);
return key($arr);
}
function array_key_last(array $arr)
{
end($arr);
return key($arr);
}
@jbafford
Copy link

jbafford commented Jan 4, 2016

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:

function array_key_first(array $arr)
{
     foreach($arr as $k => $v) {
        return $k
    }

    return null;
}

array_key_last() would still suffer from all the issues presented in the RFC.

@sergiors
Copy link

sergiors commented Jul 22, 2016

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