PHP - Ds\Stack::toArray() 函式



PHP 的 Ds\Stack::toArray() 函式用於將當前棧轉換為陣列。轉換後的陣列包含與新增到棧中的值的順序相同的元素。

PHP 中的陣列是有序對映。對映是一種將值與鍵關聯的型別。它可以被視為陣列、列表、雜湊表、字典、集合、棧、佇列等。

語法

以下是 PHP Ds\Stack::toArray() 函式的語法:

public Ds\Stack::toArray(): array

引數

此函式不接受任何引數。

返回值

此函式返回一個包含所有值的陣列,其順序與棧相同。

示例 1

以下是 PHP Ds\Stack::toArray() 函式的基本示例:

<?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);
?>

輸出

上述程式產生以下輸出:

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
)

示例 2

以下是 PHP Ds\Stack::toArray() 函式的另一個示例。我們使用此函式檢索一個包含所有值的陣列,其順序與該棧相同(["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);
?>

輸出

執行上述程式後,將顯示以下輸出:

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
廣告