// first
$value = reset($arr);
$key = key($arr);
(in that order)
See reset()
PHP Manual,
key()
PHP Manual.
unset($arr[$key]); # in case you want to remove it.
However array_pop()
PHP Manual is working with the last element:
// last
$value = end($arr);
$key = key($arr);
unset($arr[$key]); # in case you want to remove it.
See end()
PHP Manual.
For the fun:
[$value, $key] = [reset($arr), key($arr)]; // first
[$value, $key] = [end($arr), key($arr)]; // last
(PHP 7.1+)
or
list($value, $key) = array(reset($arr), key($arr)); // first
list($value, $key) = array(end($arr), key($arr)); // last
(PHP 4.3+)
or
extract(array('value' => reset($arr), 'key' => key($arr))); // first
extract(array('value' => end($arr), 'key' => key($arr))); // last
(PHP 4.3+; Caution: extract() in use!)
or
// first
reset($arr);
list($key, $value) = each($arr);
// last
end($arr);
list($key, $value) = each($arr);
(Note: The each() function is deprecated since PHP 7.2.0 and gone since PHP 8.0.0)
or whatever style of play you like ;)
Dealing with empty arrays
It was missing so far to deal with empty arrays. So it's a need to check if there is a last (first) element and if not, set the $key
to null
(as null
can not be an array key):
// first
for ($key = null, $value = null; false !== $_ = reset($arr);)
{
$value = $_;
unset($arr[$key = key($arr)]);
break;
}
unset($_);
// last
for ($key = null, $value = null; false !== $_ = end($arr);)
{
$value = $_;
unset($arr[$key = key($arr)]);
break;
}
unset($_);
This will give for a filled array like $arr = array('first' => '1st', 'last' => '2nd.');
:
string(4) "2nd." # value
string(4) "last" # key
array(1) { # leftover array
["first"]=>
string(3) "1st"
}
And an empty array:
bool(false) # value
NULL # key
array(0) { # leftover array
}
Afraid of using unset?
In case you don't trust unset()
having the performance you need (of which I don't think it's really an issue, albeit I haven't run any metrics), you can use the native array_pop()
implementation as well (but I really think that unset()
as a language construct might be even faster):
// first
reset($arr);
$key = key($arr);
$value = array_pop($arr);
// last
end($arr);
$key = key($arr);
$value = array_pop($arr);