Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first key of associative array in PHP

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.

like image 293
Dan Lugg Avatar asked Jul 14 '11 18:07

Dan Lugg


People also ask

How do you get the first key of an associative array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);

How can we get the first element of an array in PHP?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

What is key in associative array in PHP?

Associative arrays are arrays that use named keys that you assign to them.


1 Answers

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();

like image 55
adlawson Avatar answered Sep 22 '22 16:09

adlawson