I want to implement a queue in PHP, and looking at the manual , I found this example:
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
This creates the array:
array('apple', 'raspberry', 'orange', 'banana');
In this case 'banana' is at the beginning of the queue and it can be retrieved using array_pop()
.
I guess that might be the traditional approach, but is there any good reason for not reversing the data in the array as follows?
$queue = array('apple', 'orange');
$queue[] = 'banana';//avoid function call
array_push($queue, 'strawberry', 'grape');//add multiple items
$next = array_shift($queue);
Maybe it's trivial, but in that way you could avoid a function call when adding a single element. Is there some other good reason for not doing it that way?
EDIT:
It appears that my question was a little hard to understand, so to make it easier to see that my method really does implement a queue according to the FIFO principle, I wrote this code to correspond with the example from the PHP manual, producing the exact same array (except in reverse order):
$queue = array('banana', 'orange');
$queue[] = 'rasberry';
$queue[] = 'apple';
This creates the array:
array('banana', 'orange', 'rasberry', 'apple');
It's the exact same data but in reverse order, so to retreive the next item you would do so with:
$next = array_shift($queue);//The value of $next is 'banana' as before.
As already pointed out by the answers, this runs up against how most people visualize a queue. It seems that readability is the major issue. However, I find it easier to code. To me, it actually seems more natural, because the square bracket notation []
is the doorway through which my array elements enter in numerous circumstances. Therefore, implementing either a stack or a queue really isn't a question about how I mentally visualize my data. It's a question of what function to use to access the first or last element that passed through the door. For a queue it's array_shift()
, and for a stack it's pop()
.