PHP Function of the Day (2011-9-13): array_unshift

A while ago I started trying to do a tip of the day series. I kept getting distracted and sort of ran out of material. I’m going to retry this with a new twist - rather than deal with abstracts I’m going to pick a function and go over it. PHP has several hundred functions so I shouldn’t have a shortage of material.

Today’s function is [fphp]array_unshift[/fphp]

[fphp]array_unshift[/fphp] lets you prepend to an array. Consider


$myArray = array (
  'Berries',
  'Cucumbers',
  'Lettuce'
);

If we wanted to add to the end of the list, this is easy enough.


$myArray[] = 'Potatoes'; // equivalent to array_push($myArray, 'Potatoes');

But what if we want to add to the front of the list? That’s what [fphp]array_unshift[/fphp] is for.


array_unshift($myArray, 'Apples');

Keep in mind the following about [fphp]array_unshift[/fphp]: All numerical array keys will be modified to start counting from zero while literal keys won’t be touched.

Literal keys mean string keys such as $myArray[‘mykey’];

Related Functions

  • [fphp]array_shift[/fphp] removes the first element of the array and returns its value. So it undoes what array_unshift does.
  • [fphp]array_push[/fphp] appends to the end of the array. It rarely sees use in PHP because of the language shorthand shown above.
  • [fphp]array_pop[/fphp] removes the last element of the array (undoing array_push).

Might be educational if you described how these functions contribute to PHP arrays to become stacks and queues, LIFO, FIFO and all that.

I could write a book on that. But hey, this is a threaded discussion forum - people are welcome to ask questions or flesh out whatever I started the thread with.

Sorry Michael, I knew I should have fleshed it out but was pushed when I posted the reply - but upon reflection one of the points I wanted to make was that while shining a light into what may seem to be dustier corners of PHP functions is laudable, the real benefit for new users might be to actually see what problem this function solves by looking at some userland code.

i.e. hopefully evoking “I used this function to solve this particular problem” style of replies (which I do not have to hand).

However,

Imagine a stack of plates.


$plates = array(
'Adams plate',
'Bobs plate',
);

var_dump($plates);

//array
//  0 => string 'Adams plate' (length=11)
//  1 => string 'Bobs plate' (length=10)

You add a new plate to the stack. You do not lift up the stack of plates and add a plate to the bottom (normally).


array_unshift( $plates, 'Clean plate');

var_dump($plates);

//array
//  0 => string 'Clean plate' (length=11)  // it appears on the top of the stack
//  1 => string 'Adams plate' (length=11)
//  2 => string 'Bobs plate' (length=10)

When you want to take a plate you take the top one off and use that.


$first = array_shift($plates);

var_dump($plates);

//array
//  0 => string 'Adams plate' (length=11) // the clean plate has 'gone'
//  1 => string 'Bobs plate' (length=10)

echo $first ; // it has 'gone' to this variable
// Clean plate



That is an example of an array being used as a stack.

Here the rule coming into play is LIFO (Last in First Out).

To make your array work as a stack you array_unshift($plates, ‘Clean plate’) to add a new plate onto the $plates stack, and array_shift($plates) the top plate off.

When would this be important, er?

Basic issue is a queue vs. a stack. In a queue requests are handled in order they are received (here in the US we call this a “line” but queue is less ambiguous a term to use in programming since line has many meanings). A stack is handled as cups described - and this is done when the operations on the stack might affect subsequent steps.

That said, whether you pull elements from the bottom or top of the array doesn’t directly matter. If you pull and push elements off the same end of the array you are using it as a stack - and it doesn’t matter if that end is the top or bottom. If you push elements onto one end and pull off the other your using at as a queue.

Which end is which matters only for iteration, and this is where array_unshift is most useful. When you add an element to the front of an array it will be the first to be considered in a foreach loop over that array (at least until you unshift something else onto that array).