Reputation: 3445
Is there a PHP function that would 'pop' first element of array?
array_pop()
pops last element, but I'd like to pop the first.
Upvotes: 38
Views: 49350
Reputation: 11
Use key()
and unset()
.
When array's keys is Numeric, array_shift()
change array keys to started from 0.
$arr = [5 => 5, 71 => 71, 1 => 1, 8 => 8];
$first_key = key($arr);
$first_element = $arr[$first_key]; // <-- get first element of array
echo $first_element; // print '5'
unset($arr[$first_key]); // <-- delete first element of array
Upvotes: 0
Reputation: 161
While array_shift()
is definitely the answer to your question, it's worth mentioning that it can be an unnecessarily slow process when working with large arrays. (or many iterations)
After retrieving the first element, array_shift()
re-indexes all numerical keys in an array, so that the element that used to be at [1]
becomes [0]
and an element at [10000]
becomes [9999]
.
The larger the array, the more keys to re-index. And if you're iterating over large arrays, calling array_shift
on multiple iterations, the performance hit can rack up.
Benchmarks show for large arrays it's often cheaper to reverse the array order and pop the elements from the end.
$array = array_reverse($array);
$value = array_pop($array);
array_pop()
obviously doesn't need to re-index since it's taking from the end, and array_reverse()
returns a new array by simply copying the array passed to it, from back to front. array_reverse($array, true)
can be used to preserve key => value
pairs where needed.
[EDIT] I should mention, the downside to the reverse-pop method is memory consumption, where array_reverse()
generates a new array, while array_shift()
works in place. Thus takes longer.
Upvotes: 3
Reputation: 21
For me array_slice() works fine, Say:
$arr = array(1,2,3,4,5,6);
//array_slice($array,offset); where $array is the array to be sliced, and offset is the number of array elements to be sliced
$arr2 = array_slice($arr,3);//or
$arr2 = array_slice($arr,-3);//or
$arr2 = array_slice($arr,-3,3);//return 4,5 and 6 in a new array
$arr2 = array_slice($arr,0,4);//returns 1,2,3 and 4 in a new array
Upvotes: 2
Reputation: 32360
Quick Cheatsheet If you are not familiar with the lingo, here is a quick translation of alternate terms, which may be easier to remember:
* array_unshift() - (aka Prepend ;; InsertBefore ;; InsertAtBegin )
* array_shift() - (aka UnPrepend ;; RemoveBefore ;; RemoveFromBegin )
* array_push() - (aka Append ;; InsertAfter ;; InsertAtEnd )
* array_pop() - (aka UnAppend ;; RemoveAfter ;; RemoveFromEnd )
Upvotes: 38