开发者

array_pop() with Key

开发者 https://www.devze.com 2023-03-25 07:04 出处:网络
Consider the following array $array = array(\'fruit\'=> \'apple开发者_如何学运维\', \'vegetable\' => \'potato\',

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.php

Last argument true is 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.

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

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

print_r($lastElementWithKey);

Outputs:

Array
(
    [c] => 3
)


try

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


You can use end() and key() to the the key and the value, then you can pop the value.

$array = array('fruit' => 'apple', 'vegetable' => 'potato', 'dairy' => 'cheese');
$val = end($array); // 'cheese'
                    // Moves array pointer to end
$key = key($array); // 'dairy'
                    // Gets key at current array position
array_pop($array); // Removes the element
                   // Resets array pointer


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)];


This should work, just don't do it inside a foreach loop (it'll mess up the loop)

end($array); // set the array pointer to the end
$keyvaluepair = each($array);  // read the key/value
reset($array); // for good measure

Edit: Briedis suggests array_slice() which is probably a better solution


Another option:

<?php
end($array);
list($key, $value) = each($array);
array_pop($array);
var_dump($key, $value);
?>


Try this:

<?php

function array_end($array)
{
    $val = end($array);
    return array(array_search($val, $array) => $val);
}

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

echo "<pre>";
print_r(array_end($array));
?>

Output:

Array
(
    [dairy] => cheese
)
0

精彩评论

暂无评论...
验证码 换一张
取 消