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



PHP 的 Ds\Stack::count() 函式用於計算當前棧中存在的元素數量。如果此函式在空 ([]) 例項上呼叫,它將返回 0,您可以使用 isEmpty() 函式驗證棧是否為空。

語法

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

public Ds\Stack::count(): int

引數

此函式不接受任何引數。

返回值

此函式返回棧中的值的數量。

示例 1

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

<?php  
   $stack = new \Ds\Stack([2, 4, 6, 8, 10]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The number of elements present in a stack: ";
   #using count() function
   print_r($stack->count());
?>

輸出

以上程式產生以下輸出 -

The stack elements are:
Ds\Stack Object
(
    [0] => 10
    [1] => 8
    [2] => 6
    [3] => 4
    [4] => 2
)
The number of elements present in a stack: 5

示例 2

以下是 PHP Ds\Stack::count() 函式的另一個示例。我們使用此函式查詢此 (["Tutorials", "Point", "India"]) 棧中存在的元素數量 -

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

輸出

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

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The number of elements present in a stack: 3

示例 3

如果當前棧例項為空 ([]),則 count() 函式返回 0

<?php  
   $stack = new \Ds\Stack([]);
   echo "The stack elements are: \n";   
   print_r($stack);
   echo "The number of elements present in a stack: "; 
   #using count() function
   print_r($stack->count()); 
?>

輸出

執行上述程式後,它將生成以下輸出 -

The stack elements are:
Ds\Stack Object
(
)
The number of elements present in a stack: 0
php_function_reference.htm
廣告