Jonnie Grieve Digital Media: Website Blog.

Check out my very latest blogs. For more on particular topics check out the post categories.

A bit of fun with modifying arrays.

When you want to modify a simple array, you generally want to add values to it or remove items.  There are 4 common methods in the PHP arsenal that will do this.

There’s

  • push()
  • pop()
  • shift()
  • unshift();

Now these are 4 easy methods to write, but when you have a learning disability like I do the struggle to remember what each of them does is eternal. I know that I either want to add something to an array or remove it.  Does push do that? Or pop? Pop sounds like something that would separate or remove one thing from another right?

Good hunch!  But which end?  According to the documentation the value at the end of a given array will be removed.

So the array should now return

$sport = (‘Hockey’,’Cricket’);

And the array now has only 2 elements and array_pop is the method that removes a value or values from the end of an array.

So how then do you remove an element from the beginning of an array?

which would return…

So for removing elements from an array, pop() deals with the end of an array but shift removes them from the beginning.

which will return

For this we have the methods for push and shift. These methods will add one or more elements to a given array.

returns

In conclusion the methods can be summarised below.

array_unshift()  Removes an element from the beginning of an array
array_shift()  Adds an element from the end of an array
 array_pop()  Removes an element from the end of an array.
 array_push()  Adds an element to the beginning of an array.

Leave a Reply

Your email address will not be published. Required fields are marked *