// you’re reading...

Apache / PHP / MySQL

PHP Stack – An implementation of a basic data structure

php-med-transRecently, I started re-learning c++ and the topic of data structures surfaced. The conversation evolved to their usefulness in web development. Without commenting on that, I decided to partake in an exercise to implement c style functionality in a PHP OOP context. Here is the code I came up with:

/*
 * Stack - the objective of this class is to demonstrate a
 * basic stack (LIFO) data structure in PHP without using the
 * built in array functions if possible.
 */

class Stack {

	var $maxsize;
	var $items; 

	/*
	 *
	 */
	function __construct($maxsize = 10)
	{
		$this->maxsize = $maxsize;
		$this->items = array();
	}

	/*
	 * Add an element to the top of the stack.
	 */
	function push($data = NULL) {
		if(sizeof($this->items) >= $this->maxsize)
		{
			echo "Potential stack overflow detected.";
			return 0;
		}
		$this->items[] = $data;
		return 1;
	}

	/*
	 * Remove the top element of the stack.
	 */
	function pop() {
		$tmp_array = array();
		$size = sizeof($this->items);
		for($i = 0; $i < ($size - 1); $i++)
		{
			$tmp_array[] = $this->items[$i];
		}
		$this->items = $tmp_array;
	}

}

Here is a working example:

http://www.randymelder.com/test/stack1.php

Discussion

No comments for “PHP Stack – An implementation of a basic data structure”

Post a comment

 

December 2009
S M T W T F S
« Sep   Jan »
 12345
6789101112
13141516171819
20212223242526
2728293031