05c03-1.php

来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 74 行

PHP
74
字号
<?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 queuefunction 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 queuefunction 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 youfunction queue_dequeue(&$queue) {    // Just use array unshift    return array_shift($queue);}// Peek returns a copy of the front of the queue, leaving it in placefunction 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 queuefunction 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 3echo '<p>Queue size is: ', queue_size($myqueue), '</p>';// Peek at the front of the queue, it should be: Opalecho '<p>Front of the queue is: ', queue_peek($myqueue), '</p>';// Now rotate the queue, giving us: Dolphin Pelican Opalqueue_rotate($myqueue);// Remove the front element, returning: Dolphinecho '<p>Removed the element at the front of the queue: ',     queue_dequeue($myqueue), '</p>';// Now destroy it, we are done.queue_destroy($myqueue);?>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?