1 Replies - 1214 Views - Last Post: 16 August 2010 - 01:19 AM

#1 Moonbat  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 36
  • View blog
  • Posts: 424
  • Joined: 30-June 08

Stack Class

Posted 05 October 2008 - 02:19 PM

Description: A simple class for using stacks in PHP. It includes simple stack functions like push and pop, but also new functions like pad_extra and peek
stack = array();
	}
		
	public function is_empty() {
		if (empty($this->stack)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function size() {
		return count($this->stack);
	}
	
	public function push($item) { // Shove an element on the stack
		if (array_push($this->stack, $item)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function pad_to($amount, $item = 0) { // Pad the stack with $item until stack size = $amount
		if ($amount < 0 || $amount < $this->size()) {
			return FALSE;
		} else {
			while ($this->size() != $amount) {
				$this->push($item);
			}
			return TRUE;
		}
	}
	
	public function pad_extra($amount, $item = 0) { // Pad the stack with $item for $amount times
		if ($amount < 0) {
			return FALSE;
		} else {
			for ($i=0; $i<$amount; $i++) {
				$this->push($item);
			}
			unset($i);
			return TRUE;
		}
	}
	
	public function pop() { // Shoot off last item on the stack
		if (!$this->is_empty()) {
			array_pop($this->stack);
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function peek($position) { // Get certain element on the stack
		$elements = count($this->stack);
		if ($elements < $position) {
			unset($elements);
			return FALSE;
		} else {
			unset($elements);
			return $this->stack[$position];
		}
	}
	
	public function __destruct() {
		unset($this->stack);
	}
	
}
?>


Is This A Good Question/Topic? 0
  • +

Replies To: Stack Class

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4139
  • View blog
  • Posts: 13,086
  • Joined: 08-June 10

Re: Stack Class

Posted 16 August 2010 - 01:19 AM

PHP also provides native Stack and Queue classes: SplStack & SplQueue.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1