PHP - Ds\PriorityQueue::toArray() Function



The PHP Ds\PriorityQueue::toArray() function is used to convert the queue to an array. So the function returns an array which contains all the items of the priority queue.

Syntax

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

public array Ds\PriorityQueue::toArray( void )

Parameters

The toArray() function does not take any parameters.

Return Value

This function returns an array containing all values in the same order as the queue.

PHP Version

The toArray() 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::toArray() function to convert a priority queue into an array.

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();  
   
   $pqueue->push("Tutorials", 1); 
   $pqueue->push("Point", 2); 
   $pqueue->push("India", 3); 
  
   echo "The equivalent array is: \n"; 
   print_r($pqueue->toArray());
?>

Output

The above code will result something like this −

The equivalent array is: 
Array
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)

Example 2

Now the below code creates an empty array of the created PriorityQueue using the toArray() function.

<?php
   // Import the PriorityQueue class
   use Ds\PriorityQueue;

   // Create a new PriorityQueue
   $pqueue = new PriorityQueue();
   
   $array = $pqueue->toArray();
   print_r($array);  
?> 

Output

This will create the below output −

Array
(
)

Example 3

In the below PHP code we will try to use the toArray() function and add elements with different priorities and change the queue to an array.

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();  

   $pqueue->push("low priority", 1);
   $pqueue->push("medium priority", 5);
   $pqueue->push("high priority", 10);
   
   $array = $pqueue->toArray();
   print_r($array);
?> 

Output

This will generate the below output −

Array
(
    [0] => high priority
    [1] => medium priority
    [2] => low priority
)

Example 4

In the following example, we are using the toArray() function to add arrays as items in the priority queue and convert it to an array.

<?php
   // Create a new PriorityQueue
   $pqueue = new \Ds\PriorityQueue();
   $pqueue->push(["task" => "A", "priority" => 1], 1);
   $pqueue->push(["task" => "B", "priority" => 2], 2);
   $pqueue->push(["task" => "C", "priority" => 3], 3);
   
   $array = $pqueue->toArray();
   print_r($array);
?> 

Output

Following is the output of the above code −

Array
(
    [0] => Array
        (
            [task] => C
            [priority] => 3
        )

    [1] => Array
        (
            [task] => B
            [priority] => 2
        )

    [2] => Array
        (
            [task] => A
            [priority] => 1
        )

)
php_function_reference.htm
Advertisements