Stacks in php

Although not as common in PHP programs as in other programs, one fairly common data type is the last-in first-out (LIFO) stack. We can create stacks using a pair of PHP functions, array_push() and array_pop(). The array_push() function is identical to an assignment to $array[]. 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

Example of Stacks in php

$callTrace = array();
function enterFunction($name)
{
 global $callTrace;
 $callTrace[] = $name;
 echo "Entering {$name} (stack is now: " . join(' -> ', $callTrace) . ")<br />";
}
function exitFunction()
{
 echo "Exiting<br />";
 global $callTrace;
 array_pop($callTrace);
}
function first()
{
 enterFunction("first");
 exitFunction();
}
function second()
{
 enterFunction("second");
 first();
 exitFunction();
}
function third()
{
 enterFunction("third");
 second();
 first();
 exitFunction();
}
first();
third();

Entering first (stack is now: first)
Exiting
Entering third (stack is now: third)
Entering second (stack is now: third -> second)
Entering first (stack is now: third -> second -> first)
Exiting
Exiting
Entering first (stack is now: third -> first)
Exiting
Exiting

Leave a Comment