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. Unfortuna
each() still a temporary required, but potentially a much smaller overhead than using array_keys()
.
What about using array_slice (in combination with array_keys for associative arrays)?
$a = range(0,999999);
var_dump(memory_get_peak_usage());
$k = array_keys(array_slice($a, 0, 1, TRUE))[0];
var_dump(memory_get_peak_usage());
var_dump($k);
$k = array_keys($a)[0];
var_dump(memory_get_peak_usage());
Gives as output (at least with me):
int(36354360)
int(36355112)
int(0)
int(72006024)
int(0)
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.
As @TomcatExodus noted, array_shift();
expects an array passed by reference, so the first example will issue an error. Best to stick with current();
array_shift(array_keys($array))
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 );