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?
PHP | array_pop() Function. This inbuilt function of PHP is used to delete or pop out and return the last element from an array passed to it as parameter. It reduces the size of the array by one since the last element is removed from the array.
The array_pop() function deletes the last element of an array.
The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With