Let S be an associative array in PHP, I need to retrieve and extract from it the first element, both the value and the key.
I would use
value1=array_pop(S);
but it only gives me the value.
I can use
K=array_keys(S);
key1=array_pop(K);
value1=array_pop(S);
but it is complicated because it requires to have two copies of the same data. WHich is a confusing since the array is itself an element in an array of arrays. There must be a more elegant way to just read the couple key/value while extracting it.
(in that order)
See
reset()PHP Manual,key()PHP Manual.However
array_pop()PHP Manual is working with the last element:See
end()PHP Manual.For the fun:
(PHP 7.1+)
or
(PHP 4.3+)
or
(PHP 4.3+; Caution: extract() in use!)
or
(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
$keytonull(asnullcan not be an array key):This will give for a filled array like
$arr = array('first' => '1st', 'last' => '2nd.');:And an empty 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 nativearray_pop()implementation as well (but I really think thatunset()as a language construct might be even faster):