Return first key of associative array in PHP

77,192

Solution 1

Although array_shift(array_keys($array)); will work, current(array_keys($array)); is faster as it doesn't advance the internal pointer.

Either one will work though.

Update

As @TomcatExodus noted, array_shift(); expects an array passed by reference, so the first example will issue an error. Best to stick with current();

Solution 2

You can use reset and key:

reset( $array );
$first_key = key( $array );

or, you can use a function:

function firstIndex($a) { foreach ($a as $k => $v) return $k; }
$key = firstIndex( $array );

Solution 3

array_shift(array_keys($array))

Solution 4

each() still a temporary required, but potentially a much smaller overhead than using array_keys().

Share:
77,192
Dan Lugg
Author by

Dan Lugg

… 60% of the time, it works every time.

Updated on September 13, 2020

Comments

  • Dan Lugg
    Dan Lugg over 3 years

    I'm trying to obtain the first key of an associative array, without creating a temporary variable via array_keys() or the like, to pass by reference. Unfortunately both reset() and array_shift() take the array argument by reference, so neither seem to be viable results.

    With PHP 5.4 I'll be in heaven; array_keys($array)[0];, but unfortunately this of course is not an option either.

    I could create a function to serve the purpose, but I can only imagine there is some concoction of PHP's array_* functions that will produce the desired result in a single statement, that I cannot think of or come up with.

    So:

    $array = array('foo' => 'bar', 'hello' => 'world');
    
    $firstKey = assorted_functions($array); // $firstKey = 'foo'
    

    The reason for the "no reference" clause in my question is only for the fact that I assume array_keys() will be required (if there is a way passing by reference, please fire away)

    I'd use key(), but that requires a reset() as I'm not sure where the pointer will be at the time of this operation.


    Addendum

    I'm following up on a realization I had recently: as I mentioned in the comments, it'll use the memory all the same, so if that's a concern, this question hath no solution.

    $a = range(0,99999);
    var_dump(memory_get_peak_usage()); // int(8644416)
    $k = array_keys($a)[0];
    var_dump(memory_get_peak_usage()); // int(17168824)
    

    I knew this, as PHP doesn't have such optimization capabilities, but figured it warranted explicit mention.

    The brevity of the accepted answer is nice though, and'll work if you're working with reasonably sized arrays.

  • Dan Lugg
    Dan Lugg almost 13 years
    Thanks @RiaD - Strict standards, array_shift() requires an array by reference, it's a no go.
  • Dan Lugg
    Dan Lugg almost 13 years
    Thanks @Dark Slipstream - Trying to accomplish in a single statement, no reset().
  • Dan Lugg
    Dan Lugg almost 13 years
    Thanks @Orbling - True, there's a plethora of ways using a temporary, but that's what I'm trying to avoid. My struggle has gone from practical to academic :P
  • RiaD
    RiaD almost 13 years
    @Tomcat. It's get new array. So your array will be ok. Or it is trigger some errors/notices ?
  • Dan Lugg
    Dan Lugg almost 13 years
    Bingo. Thank you much on current(array_keys()). Just for future reference, an array produced by array_keys() or array_values() is of course new, and therefore it's pointer is always at the first element, correct?
  • Nahydrin
    Nahydrin almost 13 years
    You said you can use a function, use that.
  • Dan Lugg
    Dan Lugg almost 13 years
    Excellent; Thanks again. I must need more coffee, because the more I look at the answer, the more glaringly obvious it seems :) Oh, and a note on array_shift(); it doesn't. PHP 5.3.6 with error_reporting(-1) issues an error.
  • Dan Lugg
    Dan Lugg almost 13 years
    Sorry for the ambiguity; yea it issues a notice Strict Standards
  • RiaD
    RiaD almost 13 years
    OK, thank you, I will know it next time:) [Have not PHP to test]
  • Dan Lugg
    Dan Lugg almost 13 years
    Also, perhaps should have mentioned; the array is not very long, just very deep. The first dimension will likely have 3 - 5 elements, so while array_keys() is more overhead, it's not producing an enormous array.
  • Dan Lugg
    Dan Lugg almost 13 years
    "could", but don't want to, especially given the elegant solution. Thanks though :)
  • Popnoodles
    Popnoodles about 11 years
    is key($array) not faster?
  • adlawson
    adlawson about 11 years
    Maybe. It'll do the job. Use whatever you want. OP wanted something other than key() so this is it.
  • Marek Bar
    Marek Bar about 11 years
    array_shift takes array by reference so it will throw error in php 5.4
  • Developer
    Developer over 9 years
    current(array_keys($array)); is faster? or the following is faster foreach($array as $key => $val){ echo $key;break;}
  • adlawson
    adlawson over 9 years
    @Developer I dunno. Test them and find out. If I'm honest though it doesn't really matter. Use whichever one you prefer.
  • Aaron
    Aaron over 8 years
    The problem in this question is how to return the first key. The answer below by @Brian Graham should be preferred because it: moves to the first key, and returns it. Nothing else.
  • adlawson
    adlawson over 8 years
    @Aaron I don't see why it's preferential to move the internal array pointer to the first just to return the value when you don't need to. It could in fact lead to unexpected behaviour if used inside control structures like a while loop.