PHP - Ds Stack::clear() 函式



PHP 的 Ds\Stack::clear() 函式用於移除當前棧中的所有值。一旦呼叫此函式,棧將為空 ([]),沒有任何元素。

您可以使用 isEmpty() 函式驗證棧是否為空。如果當前棧為空,則此函式返回 true

語法

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

public Ds\Stack::clear(): void

引數

此函式不接受任何引數。

返回值

此函式不返回值。

示例 1

以下程式演示了 PHP Ds\Stack::clear() 函式的用法:

<?php
   $stack = new \Ds\Stack([10, 20, 30]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The stack after calling the clear() function: \n";
   #using clear() function
   $stack->clear();
   print_r($stack);
?>

輸出

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

The stack elements are:
Ds\Stack Object
(
    [0] => 30
    [1] => 20
    [2] => 10
)
The stack after calling the clear() function:
Ds\Stack Object
(
)

示例 2

以下是 PHP Ds\Stack::clear() 函式的另一個示例。我們使用此函式來移除此棧中的所有元素 (["Tutorials", "Point", "India"]):

<?php
   $stack = new \Ds\Stack(["Tutorials", "Point", "India"]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The stack after calling the clear() function: \n";
   #using clear() function
   $stack->clear();
   print_r($stack);
   echo "The number of elements present in stack is: ";
   print_r($stack->count());
?<

輸出

上述程式產生以下輸出:

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The stack after calling the clear() function:
Ds\Stack Object
(
)
The number of elements present in stack is: 0
php_function_reference.htm
廣告