Skip to content

Instantly share code, notes, and snippets.

@esase
Last active May 29, 2016 08:52
Show Gist options
  • Save esase/e6edb71d219f3ed1b8baccc5325b3a88 to your computer and use it in GitHub Desktop.
Save esase/e6edb71d219f3ed1b8baccc5325b3a88 to your computer and use it in GitHub Desktop.
Stack [data type]
<?php
class Stack
{
/**
* Items
*
* @var array
*/
protected $items = [];
/**
* Items length
*
* @var integer
*/
protected $itemsLength = 0;
/**
* Push
*
* @param mixed $value
* @return void
*/
public function push($value)
{
$this->itemsLength++;
$this->items[] = $value;
}
/**
* Pop
*
* @return mixed
* @throws Exception
*/
public function pop()
{
$lastItemIndex = $this->itemsLength - 1;
if ($lastItemIndex < 0) {
throw new Exception('There are no any items in stack');
}
$value = $this->items[$lastItemIndex];
unset($this->items[$lastItemIndex]);
$this->itemsLength--;
return $value;
}
}
$stack = new Stack();
// fill the stack
foreach (range(0, 12) as $value) {
$stack->push($value);
}
// extract from the stack
foreach (range(0, 12) as $value) {
echo $stack->pop() . '<br>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment