Dec
17
PHP Array - Stacks and State Debugger
December 17, 2007 |
In computer science, a stack is an abstract data type and data structure based on the principle of Last In First Out (LIFO). A LIFO structure can be illustrated with the example of a narrow, crowded elevator with a small door. When the elevator reaches its destination, the last people to get on have to be the first to get off. (quoted from Wikipedia)
We can create stacks using four PHP functions, let’s first take a look at them:
array_push( ) - treats array as a stack, and pushes the passed variables onto the end of array . Example of usage:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/*The above example will output:
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)*/
?>
array_pop( ) - pops and returns the last value of the array , shortening the array by one element. Example of usage:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
/*The above example will output:
Array
(
[0] => orange
[1] => banana
[2] => apple
)
*/
?>
array_shift() - shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. Example of usage:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
/*The above example will output:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
*/
?>
array_unshift() - prepends passed elements to the front of the array . Example of usage:
<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
/*The above example will output:
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
*/
?>
We use array_push( ) because it accentuates the fact that we’re working with stacks, and the parallelism with array_pop( ) makes our code easier to read. There are also array_shift( ) and array_unshift( ) functions for treating an array like a queue.
Stacks are particularly useful for maintaining state. The programm below provides a simple state debugger that allows you to print out a list of which functions have been called up to this point (i.e., the stack trace).
$call_trace = array( );
function enter_function($name) {
global $call_trace;
array_push($call_trace, $name);
echo "Entering $name (stack is now: " . join(' -> ', $call_trace) . ')<br />';
}
function exit_function( ) {
echo 'Exiting<br />';
global $call_trace;
array_pop($call_trace);
}
function first( ) {
enter_function('first');
exit_function( );
}
function second( ) {
enter_function('second');
first( );
exit_function( );
}
function third( ) {
enter_function('third');
second( );
first( );
exit_function( );
}
first( );
third( );
Similar Posts
- None Found


































