array_pop()
returns the last value of an array and removes that value from the array.
What is the function that does the opposite of array_pop()
, i.e. returns and removes the first value of an array?
A bit more detail.
array_pop()
pops an element off end of the array.
array_push()
pushes an element into the end of the array.
array_shift()
pops an element off the beginning of the array.
array_unshift()
pushes an element into the beginning of the array.
Here’s a beautiful matrix that shows each function in respect to the others. Notice the symbolic arrows.
Beginning End
Pop from <-array_shift()
array_pop()
->
Push into ->array_unshift()
array_push()
<-
It was real uneasy to create it with SO’s markup restrictions. Click on edit to check out the source (and of course feel free to enhance it)!
So. When trying to memorize all 4 functions, it was very easy for me to learn what array_pop()
does: it just pops an element off the end of array. Naturally, the functionality of the complementary array_push()
was absolutely clear from the first shot too: it pushes an element back into the end. However, the two opposite brothers array_shift()
and array_unshift()
kept giving me hard time when I was trying to remember which one pops and which one pushes. :-/ I had to constantly look it up.
Funny, the solution I came up with was simply the letter “U”. Those that have it: array_pUsh()
and array_Unshift()
- pUsh. The other two - pop. Easy-peasy!
Hope this helps anyone!
From the php manual:-
array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.
I know this is a trivial question but I did a Google search for opposite of array_pop() and nothing popped up, so I thought I'd share the question on here and it might save lots of people about 4 seconds each :)
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