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?
A small change to what Sarfraz posted is:
I like the "list" example, but "list" only works on the left-hand-side of an assignment. If we don't want to assign a variable, we would be forced to make up a temporary name, which at best pollutes our scope and at worst overwrites an existing value:
The above will overwrite any existing value of $x, and the $x variable will hang around as long as this scope is active (the end of this function/method, or forever if we're in the top-level). This can be worked around using call_user_func and an anonymous function, but it's clunky:
If we use anonymous functions like this, we can actually get away with reset and array_shift, even though they use pass-by-reference. This is because calling a function will bind its arguments, and these arguments can be passed by reference:
However, this is actually overkill, since call_user_func will perform this temporary assignment internally. This lets us treat pass-by-reference functions as if they were pass-by-value, without any warnings or errors:
I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with
array_keys()
orarray_values()
, so I usually define this:I would do
echo current($array)
.A kludgy way is:
Output: