array_pop() with Key

Viewed 22344

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?

7 Answers

Why not using new features? The following code works as of PHP 7.3:

// As simple as is!
$lastPair = [array_key_last($array) => array_pop($array)];

The code above is neat and efficient (as I tested, it's about 20% faster than array_slice() + array_pop() for an array with 10000 elements; and the reason is that array_key_last() is really fast). This way the last value will also be removed.

Tip: You can also extract key and value separately:

[$key, $value] = [array_key_last($array), array_pop($array)];
Related