PHP - Ds\Queue::peek() Function
The PHP Ds\Queue::peek() function is used to retrieve a value at the front of a queue without removing it. The front value of the queue refers to the top value. If the current queue is empty ([]), this function will throw an "UnderflowException".
Syntax
Following is the syntax of the PHP Ds\Queue::peek() function −
public Ds\Queue::peek(): mixed
Parameters
This function does not accept any parameters.
Return value
This function returns a value at the front of a queue.
Example 1
The following is the basic example of the PHP Ds\Queue::peek() function −
<?php $queue = new \Ds\Queue([10, 20, 30, 40, 50]); echo "The queue elements are: \n"; print_r($queue); echo "The peek element in queue is: "; print_r($queue->peek()); ?>
Output
The above program produces the following output −
The queue elements are:
Ds\Queue Object
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
[4] => 50
)
The peek element in queue is: 10
Example 2
Following is another example of the PHP Ds\Queue::peek() function. We use this function to retrieve the top element of this queue (["Tutorials", "Point", "India"]) −
<?php $queue = new \Ds\Queue(["Tutorials", "Point", "India"]); echo "The queue elements are: \n"; print_r($queue); echo "The peek element in queue is: "; print_r($queue->peek()); ?>
Output
After executing the above program, the following output will be displayed −
The queue elements are:
Ds\Queue Object
(
[0] => Tutorials
[1] => Point
[2] => India
)
The peek element in queue is: Tutorials
Example 3
If the current queue is empty ([]), this function will throw an "UnderflowException" −
<?php $queue = new \Ds\Queue([]); echo "The queue elements are: \n"; print_r($queue); echo "The peek element in queue is: "; print_r($queue->peek()); ?>
Output
Once the above program is executing, it throws the following exception −
The queue elements are:
Ds\Queue Object
(
)
The peek element in queue is: PHP Fatal error: Uncaught UnderflowException:
Unexpected empty state in C:\Apache24\htdocs\index.php:6
Stack trace:
#0 C:\Apache24\htdocs\index.php(6): Ds\Queue->peek()
#1 {main}
thrown in C:\Apache24\htdocs\index.php on line 6