This week I needed to run a series of procedures in a standard first in, last out methodology. I could, of course, have used an array for this, however, I decided to try out a stack.
Spl data structures are often over looked in PHP. However, as PHP advances into a more object orientated environment, I think it is important that we stand up and take note because structures allow us (as web developers) to use traditional programming data structures in our code.
Here’s how we would initiate a stack:
$stack = new SplStack();
A stack is essentially an array and has two primary functions:
$stack->push( $mixed );
$stack->pop();
Imagine a pile of books on a desk. You can put a book on top of the pile and take a book from the top of the pile and nothing else (without things getting messy). This is essentially how a stack works. The “push” method will put a metaphorical ”book” on top of the pile and the “pop” method will remove whatever is at the top of the pile. Its that simple.
So, what else can we do with SplStack? The SplStack class has three implementations. Iterator, ArrayAccess and Countable. The Iterator implementation is very important as it allows us to iterate over each element stored in the stack. Por ejemplo:
$stack = new SplStack();
$stack->push( 1 );
$stack->push( 2 );
$stack->push( 3 );
foreach( $stack as $s ){
echo $stack->pop();
}
// This would output: 321
ArrayAccess allows us to do exactly that. Here is an example:
$stack = new SplStack();
$stack[] = 1;
$stack[] = 2;
$stack[] = 3;
Finally, Countable simply allows us to count how many elements are stored in the stack:
// Using the above $stack instance
echo $stack->count();
// This would output an integer of 3
In the coming posts, I will write more about Spl data structures. Next time, I will focus on the class: SplQueue.




