Consider the following array
$array = array('fruit' => 'apple',
'vegetable' => 'potato',
'dairy' => 'cheese');
I wanted to use array_pop to get the last key/value pair.
However, one will note that after the following
$last = array_pop($array);
var_dump($last);
It will output only the value (string(6) "cheese")
How can I “pop” the last pair from the array, preserving the key/value array structure?
Check out
array_slice()http://php.net/manual/en/function.array-slice.phpLast argument
trueis to preserve keys.When you pass the offset as negative, it starts from the end. It’s a nice trick to get last elements without counting the total.
Outputs: