I have an array:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
I would like to get the first element of this array. Expected result: string apple
One requirement: it cannot be done with passing by reference, so array_shift
is not a good solution.
How can I do this?
Some arrays don't work with functions like
list
,reset
orcurrent
. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.If you want to pull the first value regardless of the array, you can short-circuit an iterator:
Your value will then be available in
$value
and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).You can grab the key this way too:
If you're calling this from a function, simply return early:
Most of these work! BUT for a quick single line (low resource) call:
Although this works, and decently well, please also see my additional answer: https://stackoverflow.com/a/48410351/1804013
Old post but anyway... I imagine the author just was looking for a way to get the first element of array after getting it from some function (mysql_fetch_row for example) without generating a STRICT "Only variables should be passed by reference". If it so, almos all ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:
This way you don't get the STRICT message on screen neither in logs and you don't create any additional arrays. It works with both indexed AND associative arrays
If you don't want to lose the current pointer position, just create an alias for the array.
current($array)
can get you first element of an array, according to PHP Manual
So it works until you have re-positioned array pointer, otherwise you ll have to reset the array.