CopyPastehas never been so tasty!

Stack handling in PHP

by anonymous

  • 0
  • 0
  • 0
55 views


http://codingvilla.com/stack-handling-php-single-article-674.aspx

Stack:

 

 

A stack is a last in first out (LIFO) type linear data structure. Items can only be inserted from the top and removed from the top. Two important stack operations involve pushing data onto a stack and popping data off the stack.

 

Code:

 

1.    <?php

2.    function &stack_initialize() {

3.    $new_array = array();

4.    return  $new_array;

5.    }

6.    function stack_destroy(&$stack) {

7.    unset($stack);

8.    }

9.    function stack_push_value(&$stack, $value) {

10.  $stack[] = $value;

11.  }

12.  function stack_pop_value(&$stack) {

13.  return array_pop($stack);

14.  }

15.  function stack_peek_value(&$stack) {

16.  return $stack[count($stack)-1];

17.  }

18.  function count_size(&$stack) {

19.  return count($stack);

20.  }

21.  function stack_swap(&$stack) {

22.  $num = count($stack);

23.  if ($num > 1) {

24.  $second = $stack[$num-2];

25.  $stack[$num-2] = $stack[$num-1];

26.  $stack[$num-1] = $second;

27.  }

28.  }

29.  function stack_dup(&$stack) {

30.  $stack[] = $stack[count($stack)-1];

31.  }

32.  $my_fisrt_stack =& stack_initialize();

33.  stack_push_value($my_fisrt_stack, 78);

34.  stack_push_value($my_fisrt_stack, 85);

35.  stack_push_value($my_fisrt_stack, 6);

36.  stack_push_value($my_fisrt_stack, 4);

37.  stack_dup($my_fisrt_stack);

38.  echo "Stack size is: " .count_size($my_fisrt_stack)."<br/>";

 

39.  echo "Popped value is: ".stack_pop_value($my_fisrt_stack)."<br/>";

40.  echo stack_swap($my_fisrt_stack);

41.  echo "Current top element is:" .stack_peek_value($my_fisrt_stack);

42.  stack_destroy($my_fisrt_stack);

43.  ?>

 

 

 

Output:

 

Stack size is: 5

Popped off the value: 4

Current top element is:6

 

 

Explanation:

 

 

On line 32 we have declare and initialize an array $my_fisrt_stack. Then perform that array stack type operations. On line 33 to line 36 we have pushed values into stack. The value that is inserted lastly in to the stack comes out firstly. Then on line 38 we have checked the size of the stack. On line 39 we have pop first value in the stack first means that is at last index. On line 40 we have swapped the elements to move pointer to the next location that is 6. Now the current top element is 6 and if we do not call this function then the current top element is ‘4’.

Add A Comment: