Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds\Queue::pop() Function



The PHP Ds\Queue::pop() function is used to remove and return a value from the front (top) of a queue. However, a "queue" is a linear data structure that follows the FIFO (First In First Out) order, which means that values are inserted at the back and removed from the front. So, the values that are added first will be removed first.

If the current queue is empty ([]), this function will throw an "UnderflowException".

Syntax

Following is the syntax of the PHP Ds\Queue::pop() function −

public Ds\Queue::pop(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the removed value that was at the front of a queue.

Example 1

Following is the basic example of the PHP Ds\Queue::pop() function −

<?php  
   $queue = new \Ds\Queue([10, 20, 30, 40, 50]);
   echo "The original queue is: \n";
   print_r($queue);
   echo "The removed element: ";
   #using pop() function
   print_r($queue->pop());
?>

Output

The above program produces the following output −

The original queue is:
Ds\Queue Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The removed element: 10

Example 2

Following is another example of the PHP Ds\Queue::pop() function. We use this function to retrieve the removed element at the front (top) of this queue (['a', 'b', 'c', 'd']) −

<?php  
   $queue = new \Ds\Queue(['a', 'b', 'c', 'd']);
   echo "The original queue is: \n";
   print_r($queue);
   echo "The removed element: ";
   #using pop() function
   print_r($queue->pop());
   echo "\nThe queue after pop: \n";
   print_r($queue);
?>

Output

After executing the above program, the following output will be displayed −

The original queue is:
Ds\Queue Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
The removed element: a
The queue after pop:
Ds\Queue Object
(
    [0] => b
    [1] => c
    [2] => d
)

Example 3

If the current queue is empty ([]), this function throws an "UnderflowException" −

<?php  
   $queue = new \Ds\Queue([]);
   echo "The original queue is: \n";
   print_r($queue);
   echo "The removed element: ";
   #using pop() function
   print_r($queue->pop());
   echo "\nThe queue after pop: \n";
   print_r($queue);
?>

Output

Once the above program is executed, it throws the following exception −

The original queue is:
Ds\Queue Object
(
)
The removed element: PHP Fatal error:  Uncaught UnderflowException: 
Unexpected empty state in C:\Apache24\htdocs\index.php:7
Stack trace:
#0 C:\Apache24\htdocs\index.php(7): Ds\Queue->pop()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
Advertisements