Even though PHP has an intrinsic array data type you as the programmer have the ability to manipulate arrays in several different ways. PHP can manipulate the array()
data type as though it were a stack data structure through two simple functions, array_push()
and array_pop()
which just reinforces how versatile PHP can be. This article talks about the former function, array_push()
specifically.
The stack data structure works just like a stack of dinner plates. It is a last-in, first-out data structure. Imagine someone is handing you dinner plates as they wash them up in the kitchen sink. You towel off the freshly washed dinner plate, and put it on to the work surface. When you’re handed the second plate, you dry that one off and place it neatly on top of the first dinner plate. You do the same with the third, placing it on the second dinner plate. And so on and so forth for all of the dinner plates you are given by the washer-upper until you have a precarious, teetering stack of china dinner plates threatening to topple over on you.
When someone else comes in to the kitchen and asks for a dinner plate, you take the very last one you dried from the top of the stack and hand it off to them. If you’re asked for multiple dinner plates, you take them off the towering stack of china, one at a time, in the reverse order that you placed them on there, the last one you dried is the first one that gets taken off. When you have no more dinner plates, the stack is empty.
Your stack can be as tall as your kitchen, so long as you have enough space between the top of the last plate you put on the stack and the very ceiling of the kitchen itself.
Similarly, in a stack data structure, you push items on to the top of the stack as they are handed to you, and you pop items from the top of the stack when asked for them, this is done with the two PHP functions array_push()
and array_pop()
respectively. You can only ever push one item at a time, and you can only ever pop one item at a time. If you need to push multiple items on to the stack, you iterate over your collection of items, say with a foreach
loop, pushing items on to the stack as you go. You can push as many items on to your stack data structure as you have memory available. Once you have run out of memory, i.e. reached the kitchen ceiling in our dinner plate analogy, the only way to add more items to the stack is to pop some old items off first.
Of course, a PHP array can work like a stack data structure, but that does not mean it has to always be treated like a stack data structure. That’s the versatility of PHP. You can treat arrays as lists, and queues (with array push and array shift), and stacks (with array push and array pop), and yes, even boring old arrays, without having to create them any differently as you normally would create an array. You merely call different functions, with the array as a parameter to the function, to perform the appropriate action.
array_push()
Function Definitionint array_push(array &$source_array, mixed $item [, mixed $item...])
source_array |
Required |
The source array that will have a value pushed on to the end of it. |
item |
Required |
The item to be pushed on to the end of the source array |
Returns the new number of elements in the source array after the push operation.
Invoking this function when the first argument is not an array()
data type will raise a warning.
If all you need to do is add a single item to the end of the array, i.e. the top of the stack, the code:
$source_array[] = $item;
is marginally faster as you do not need to invoke a function nor perform any specific checks about whether source_array
is an actual array()
data type. You save the overhead of calling a function to do the same thing as you could have written yourself.
That said, if you want to maintain a consistent style of how you access a particular array, that is, it is explicit that you are treating the array as a stack data structure by how you address it, e.g. by always using array_push()
and array_pop()
to push and pop items on to the stack, then a function call can make your code more readable and maintainable. This is a downside to the flexibility of PHP, you can easily tie yourself in knots with all of the rope you are given to solve a particular problem in a dozen different ways.
You should also be aware that using:
array_push($source_array, $item);
as mentioned earlier, will raise a warning if the data type is not an array or is NULL
. But using:
$source_array[] = $item;
Will actually create a new array variable and assign the first element to be the item you want pushed on to the end of the array.
This slightly different behaviour is again something you need to be aware of as it can easily catch you out if you are not watching for it, causing an error in your program due to unexpected behaviour. One more reason to maintain a consistent usage of array_push()
and array_pop()
when treating an array as a stack data structure.
If you are not in the habit of forward declaring and initialising your variables before use, the form:
$source_array[] = $item;
Is the way to go, but preferably, explicitly stating:
$source_array = array();
before you use the array is good programming practice, because even though PHP lets you skip that declaration and initialisation part, doing so can lead to difficult to debug and hard to maintain source code that exhibits unexpected behaviour when executed.
It’s the little things like forward declaring and proper initialising of your variables which elevate the professional software developer above the hacker (negative connotation of hacker as someone who just hacks around and isn’t particularly good at what they do, rather than the positive identification of hacker who is very skilled at what they do because they know what they are doing and why they are doing it and why something works the way it does) who just throws stuff up on the screen in the hope that it’ll all work out somehow.
This example demonstrates how to push an element on to a stack by treating a PHP array as a stack data structure.
array_push()
function to add one new element to the array. <?php
// allocate a small array of integers
$stack = array(1, 2, 3);
// push a single element on to the end of the array
array_push($stack, 4);
// output each number on the stack
print_r($stack);
?>
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
As you can see the output of the program has added the new element, in this case the number four, as the fourth element of the array, i.e. it has been added to the end of the array.
The previous example showed how to just push a single element on to the end of the array. But what if you want to push multiple elements all at once?
The following example demonstrates pushing multiple elements on to the end of the array in the order in which they are given in the function call.
array_push()
function to add several new elements to the array. <?php
// allocate a small array of integers
$stack = array(1, 2, 3);
// push multiple elements on to the end of the array
array_push($stack, 4, 5, 6);
// output each number on the stack
print_r($stack);
?>
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
The output of the program shows that the $stack array has grown from the first three integers given during the declaration of the array, to now include six integers, all of them appended to the end of the array in the order in which they were specified.
Treating a simple array()
data type as though it were a stack provides an immense amount of flexibility in how you solve a particular programming problem. There are a few caveats to be aware of, as already discussed in this article, such as consistency in accessing the array, which are all part of good programming practises. The power of just declaring your data structure and getting on with solving the problem at hand whilst the computer worries about the details is very enabling for programmers.