Entry
How do I implement a stack?
How do I emulate PERL's push() and pop()?
May 26th, 2000 02:09
Bruce Morrison, Leon Atkinson,
The following functions implement a stack (First In, Last Out)
in PHP3. If using PHP4, use the built-in functions
(array_push, array_pop).
Warning: This implementation of a stack does not work if you push after
popping. Try
print(push('Apple', $myArray) . " items on stack<BR>\n");
print(push('Ball', $myArray) . " items on stack<BR>\n");
print(push('Cat', $myArray) . " items on stack<BR>\n");
print(pop($myArray) . "<BR>\n");
print(pop($myArray) . "<BR>\n");
print(pop($myArray) . "<BR>\n");
print(push('Apple', $myArray) . " items on stack<BR>\n");
print(push('Ball', $myArray) . " items on stack<BR>\n");
print(push('Cat', $myArray) . " items on stack<BR>\n");
print(pop($myArray) . "<BR>\n");
print(pop($myArray) . "<BR>\n");
print(pop($myArray) . "<BR>\n");
after defining the functions.
to fix
//removes item from stack
function pop(&$array)
{
//get size of stack
$count = count($array);
//get the item
$item = $array[$count - 1];
//delete it from the stack
for ($i = 0; $i <= $count-2; $i++) {
$tmp_array[]=$array[$i];
}
$array=$tmp_array;
//return the item
return($item);
}
<?
//adds an item to the stack
function push($item, &$array)
{
//add item to end of array
$array[] = $item;
//return the size of the stack
return(count($array));
}
//removes item from stack
function pop(&$array)
{
//get size of stack
$count = count($array);
//get the item
$item = $array[$count - 1];
//delete it from the stack
unset($array[$count - 1]);
//return the item
return($item);
}
print(push('Apple', $myArray) . " items on stack<BR>\n");
print(push('Ball', $myArray) . " items on stack<BR>\n");
print(push('Cat', $myArray) . " items on stack<BR>\n");
print(pop($myArray) . "<BR>\n");
print(pop($myArray) . "<BR>\n");
print(pop($myArray) . "<BR>\n");
?>