Skip to content

Instantly share code, notes, and snippets.

@thachp
Last active August 29, 2015 14:23
Show Gist options
  • Save thachp/17cc4864d57434d258d7 to your computer and use it in GitHub Desktop.
Save thachp/17cc4864d57434d258d7 to your computer and use it in GitHub Desktop.
Stack implementation using array
<?php
/**
* Implement a stack using array. LIFO. No SPL.
* @author thachp
*/
class Stack {
// dynamic type
private $_stack = array();
// Move the first item in the array out.
public function pop($item)
{
array_shift($this->_stack);
}
// Add item to the last item.
public function push($item)
{
array_unshift($this->_stack, $item);
}
// get stack
public function getStack()
{
return $this->_stack;
}
}
$stack = new Stack();
$stack->push('a');
$stack->push('b');
$stack->push('c');
// expect an array of c,b,a
print_r($stack->getStack());
$stack->pop();
// expect an array of b,a
print_r($stack->getStack());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment