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?
Simply do:
PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:
Apart from being semantically meaningful, these functions don't even move the array pointer (as
foreach
would do).Having the keys, one can get the values by the keys directly.
Examples (all of them require PHP 7.3+)
Getting the first/last key and value:
Getting the first/last value as one-liners, assuming the array cannot be empty:
Getting the first/last value as one-liners, with defaults for empty arrays:
Use:
By default,
array_slice
does not preserve keys, so we can safely use zero as the index.Suppose:
Just use:
to get first element or
to get first key.
Or you can unlink the first if you want to remove it.
This is much more efficient than
array_values()
because theeach()
function does not copy the entire array.For more info see http://www.php.net/manual/en/function.each.php
Also worth bearing in mind the context in which you're doing this, as an exhaustive check can be expensive and not always necessary.
For example, this solution works fine for the situation in which I'm using it (but obviously can't be relied on in all cases...)