Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_pop() with Key

Tags:

arrays

php

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?

like image 990
Steve Robbins Avatar asked Aug 03 '11 21:08

Steve Robbins


People also ask

How to array pop in PHP?

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.

How to remove last row from array in PHP?

The array_pop() function deletes the last element of an array.

What does Array_splice () function do give an example?

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


2 Answers

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 ) 
like image 64
Mārtiņš Briedis Avatar answered Oct 05 '22 22:10

Mārtiņš Briedis


try

end($array); //pointer to end each($array); //get pair 
like image 41
RiaD Avatar answered Oct 05 '22 21:10

RiaD