Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the function that does the opposite of array_pop()?

Tags:

php

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?

like image 396
rgvcorley Avatar asked Jul 08 '12 23:07

rgvcorley


2 Answers

A bit more detail.

Functionality

  1. array_pop()pops an element off end of the array.

  2. array_push() pushes an element into the end of the array.

  3. array_shift() pops an element off the beginning of the array.

  4. array_unshift() pushes an element into the beginning of the array.

Beautiful Matrix

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

Shift VS. Unshift confusion

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!

like image 133
Geo Avatar answered Nov 15 '22 12:11

Geo


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

like image 26
rgvcorley Avatar answered Nov 15 '22 12:11

rgvcorley