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?
Hope this helps. :)
Get first element:
Get last element
I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get 'apple'.
This is a little late to the game, but I was presented with a problem where my array contained array elements as children inside it, and thus I couldn't just get a string representation of the first array element. By using PHP's
current()
function, I managed this:Thanks to all the current solutions helped me get to this answer, I hope this helps someone sometime!
This is not soo simple response in real world. Supost that we have this examples of possibles responses that you can find in some libraries.
Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.
In my opinion, you have should that handler only with arrays.
Now talking about performance, assuming that we have always array, like this:
array_shift is more fast that reset, that is more fast that [count()-1] and this three are more fast that array_values and array_slice
Original answer, but costly (O(n)):
In O(1):
Edited with suggestions from comments for other use cases etc...
If modifying (in the sense of resetting array pointers) of
$array
is not a problem, you might use:This should be theoretically more efficient, if a array "copy" is needed:
With PHP 5.4+ (but might cause an index error if empty):