Skip to content

Instantly share code, notes, and snippets.

@mhmohon
Last active April 4, 2022 05:54
Show Gist options
  • Save mhmohon/aeab8bacc0bfc24683780512afcb8f00 to your computer and use it in GitHub Desktop.
Save mhmohon/aeab8bacc0bfc24683780512afcb8f00 to your computer and use it in GitHub Desktop.
<?php
class stack {
protected $stack;
protected $limit;
public function __construct($limit = 10, $initial = array()) {
$this->stack = $initial; // initialize the stack
$this->limit = $limit; // stack can only contain this many items
}
public function push($item) {
if (count($this->stack) < $this->limit) {
array_unshift($this->stack, $item); // prepend item to the start of the array
} else {
echo "Stack is full";
}
}
public function pop() {
if ($this->isEmpty()) {
echo "Stack is empty";
} else {
return array_shift($this->stack); // pop item from the start of the array
}
}
public function top() {
return current($this->stack);
}
public function isEmpty() {
return empty($this->stack);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment