Learning about PHP stacks and queues

  • 2020-06-15 07:53:33
  • OfStack

In PHP arrays are often used as stack (lifO: LIFO) and queue (fifO: FIFO) structures. PHP provides a set of functions for push and pop (stack) and shift and unshift (queue) to manipulate array elements. Stacks and queues are widely used in practice.
We can start by looking at the stack:

 <?php
   $arr = array();
   array_push($arr,'aaa');
   array_push($arr,'bbb');
   $arr.pop();
   print_r($arr);
?>
 

If you want to use arrays as queues (FIFO), you can use array_unshift() to add elements and array_shift() to delete:

<?php
   $arr = array();
   array_unshift($arr,'aaa');
   array_unshift($arr,'bbb');
   print_r($arr);
   array_shift($arr);
   print_r($arr);
?>


Related articles: