Stacks, Queues and Sets

Arrays can be used in a number of different ways. This can include stacks, queues, and sets. I personally don’t use these functions very often but It can’t hurt to go over them for before taking the Zend Certification exam.

Stacks are a Last in, First out (LIFO) structure which means that the first element you put on the stack is only available when all other elements are removed. Just like a stack of papers. This is acheived by using the array_push and array_pop functions.

Here is a simple little example:

  1.  
  2. $stack_array = array();
  3. array_push($stack_array,"zend");
  4. //You can add multiple values at once
  5. array_push($stack_array,"php","certification");
  6. $last_in = array_pop($stack_array); //last_in will house "certification"
  7.  

The array_push function is very similar to “$a[] = $value” and the latter is actually much faster because no function call is made.

Next up is the queue which is a first in first out data structure. Just like a line at a movie theater, the first elements added to the queue get their choice of seats. Queue manipulation is acheived using the array_shift, array_unshift, and any of the functions outlined above.

The array_shift function will remove and return the element from the front of the array and the array_unshift will prepend an element to the front of the array. If both these functions are used together then the array will work like a sort of backwards stack but if array_shift is used with array_push or if array_unshift is used with array_pop then the array will act as a queue.

  1.  
  2. $stack_array = array(’zend’, ’php’, ’cert’);
  3. $first = array_shift($stack); //$first now houses ‘zend’
  4. array_unshift($stack, ’dont fail’); //adds ‘dont fail’ to the beginning of the array.
  5.  

There are a few functions that mimic set functionality using php arrays. These are array_diff(), array_intersect, array_intersect_key(), array_intersect_assoc(),array_intersect_ukey(), and array_intersect_uassoc().

The function array_diff() is used to compute the difference between two arrays: