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

PHP - Ds\PriorityQueue::copy() Function



The PHP Ds\PriorityQueue::copy() function is used to return a shallow copy of the queue. And this function does not accept any argument.

Syntax

Below is the syntax of the PHP Ds\PriorityQueue::copy() function −

public Ds\PriorityQueue::copy(): Ds\PriorityQueue

Parameters

The copy() function does not take any parameters.

Return Value

This function returns a new Ds\PriorityQueue object that is a shallow copy of the original.

PHP Version

The copy() function is available from version 1.0.0 of the Ds extension onwards.

Example 1

Here we will show you the basic example of the PHP Ds\PriorityQueue::copy() function to create a shallow copy of the queue.

<?php
   // Create a new instance of PriorityQueue
   $pqueue = new \Ds\PriorityQueue();  
   $pqueue->push("Tutorials", 1); 
   $pqueue->push("Point", 2); 
   $pqueue->push("India", 3); 
  
   print_r($pqueue->copy());
?>

Output

The above code will result something like this −

Ds\PriorityQueue Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)

Example 2

Now we will use copy() function to copy an empty queue which is created using the \Ds\PriorityQueue class.

<?php
   // Create a new instance of the PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   $copyQueue = $pqueue->copy();
   
   print_r($pqueue);
   print_r($copyQueue);
?> 

Output

This will generate the below output −

Ds\PriorityQueue Object
(
)
Ds\PriorityQueue Object
(
)

Example 3

Now the below code we will use copy() function to show how changes in the original queue is not affecting the copied queue. So after adding an extra element in the actual queue will not affect the copied queue.

<?php
   // Create a new instance of the PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   $pqueue->push("Task 1", 1);
   $pqueue->push("Task 2", 2);
   
   $copyQueue = $pqueue->copy();
   $pqueue->push("Task 3", 3);
   
   print_r($pqueue);
   print_r($copyQueue);
?> 

Output

This will create the below output −

Ds\PriorityQueue Object
(
    [0] => Task 3
    [1] => Task 2
    [2] => Task 1
)
Ds\PriorityQueue Object
(
    [0] => Task 2
    [1] => Task 1
)

Example 4

In the following example, we are using the copy() function to iterate over a copied Ds\PriorityQueue.

<?php
   // Create a new instance of the PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   $pqueue->push("Task 1", 1);
   $pqueue->push("Task 2", 2);
   
   $copyQueue = $pqueue->copy();
   
   foreach ($copyQueue as $value) {
       echo $value . "\n";
   }
?> 

Output

Following is the output of the above code −

Task 2
Task 1
php_function_reference.htm
Advertisements