Skip to content

Instantly share code, notes, and snippets.

@agenticsim
Created October 23, 2013 08:22

Revisions

  1. sunseesiu created this gist Oct 23, 2013.
    59 changes: 59 additions & 0 deletions queue.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    <?php
    // A library to implement queues in PHP via arrays
    // The Initialize function creates a new queue:
    function &queue_initialize() {
    // In this case, just return a new array
    $new = array();
    return $new;
    }
    // The destroy function will get rid of a queue
    function queue_destroy(&$queue) {
    // Since PHP is nice to us, we can just use unset
    unset($queue);
    }
    // The enqueue operation adds a new value unto the back of the queue
    function queue_enqueue(&$queue, $value) {
    // We are just adding a value to the end of the array, so can use the
    // [] PHP Shortcut for this. It's faster than using array_push
    $queue[] = $value;
    }
    // Dequeue removes the front of the queue and returns it to you
    function queue_dequeue(&$queue) {
    // Just use array unshift
    return array_shift($queue);
    }
    // Peek returns a copy of the front of the queue, leaving it in place
    function queue_peek(&$queue) {
    // Return a copy of the value found in front of queue
    // (at the beginning of the array)
    return $queue[0];
    }
    // Size returns the number of elements in the queue
    function queue_size(&$queue) {
    // Just using count will give the proper number:
    return count($queue);
    }
    // Rotate takes the item on the front and sends it to the back of the queue.
    function queue_rotate(&$queue) {
    // Remove the first item and insert it at the rear.
    $queue[] = array_shift($queue);
    }
    // Let's use these to create a small queue of data and manipulate it.
    // Start by adding a few words to it:
    $myqueue =& queue_initialize();
    queue_enqueue($myqueue, 'Opal');
    queue_enqueue($myqueue, 'Dolphin');
    queue_enqueue($myqueue, 'Pelican');
    // The queue is: Opal Dolphin Pelican
    // Check the size, it should be 3
    echo '<p>Queue size is: ', queue_size($myqueue), '</p>';
    // Peek at the front of the queue, it should be: Opal
    echo '<p>Front of the queue is: ', queue_peek($myqueue), '</p>';
    // Now rotate the queue, giving us: Dolphin Pelican Opal
    queue_rotate($myqueue);
    // Remove the front element, returning: Dolphin
    echo '<p>Removed the element at the front of the queue: ',
    queue_dequeue($myqueue), '</p>';
    // Now destroy it, we are done.
    queue_destroy($myqueue);
    ?>