Steve Robbins Steve Robbins - 3 months ago 20
PHP Question

array_pop() with Key

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?

Answer

Check out array_slice() http://php.net/manual/en/function.array-slice.php

print_r(array_slice(array("a" => "1", "b" => 2, "c" => 3), -1, 1));
Comments