带键的 array_pop()

2022-08-30 14:54:01

请考虑以下数组

$array = array('fruit'     => 'apple',
               'vegetable' => 'potato',
               'dairy'     => 'cheese');

我想使用array_pop来获取最后一个键/值对。

但是,人们会注意到,在以下之后

$last = array_pop($array);

var_dump($last);

它将仅输出值 (string(6) "cheese")

如何从数组中“弹出”最后一对,同时保留键/值数组结构?


答案 1

退房 http://php.net/manual/en/function.array-slice.phparray_slice()

最后一个参数是保留密钥。true

将偏移量作为负数传递时,它将从末尾开始。在不计算总数的情况下获取最后元素是一个很好的技巧。

$array = [
    "a" => 1,
    "b" => 2,
    "c" => 3,
];

$lastElementWithKey = array_slice($array, -1, 1, true);

print_r($lastElementWithKey);

输出:

Array
(
    [c] => 3
)

答案 2

尝试

end($array); //pointer to end
each($array); //get pair