PHP - Ds\Stack::toArray() Function



The PHPDs\Stack::toArray()function is used to convert the current stack to an array. The converted array contains the elements in the same order as the values that were added to the stack.

An array in PHP is an ordered map. A map is a type that associates values with keys. It can be treated as an array, list, hash table, dictionary, collection, stack, queue, etc.

Syntax

Following is the syntax of the PHP Ds\Stack::toArray() function −

public Ds\Stack::toArray(): array

Parameters

This function does not accept any parameter.

Return value

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

Example 1

The following is the basic example of the PHP Ds\Stack::toArray() function −

<?php 
   $stack = new \Ds\Stack([1, 2, 3, 4, 5]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The array is: \n";
   #using toArray() function
   $arr = $stack->toArray();
   print_r($arr);
?>

Output

The above program produces the following output −

The stack elements are:
Ds\Stack Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
The array is:
Array
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

Example 2

Following is another example of the PHP Ds\Stack::toArray() function. We use this function to retrieve an array containing all values in the same order as this stack (["Tutorials", "Point", "India"]) −

<?php 
   $stack = new \Ds\Stack([]);
   $stack->push("Tutorials", "Point", "India");
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The array is: \n";
   #using toArray() function
   $arr = $stack->toArray();
   print_r($arr);
?>

Output

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

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The array is:
Array
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
php_function_reference.htm
Advertisements