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



PHP 的Ds\Stack::isEmpty()函式用於確定當前棧是否為空。空棧指的是其中0個元素。

如果當前例項為空([]),則此函式返回布林值“true”,否則返回“false”。如果在空棧上呼叫count()函式,它將返回0

語法

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

public Ds\Stack::isEmpty(): bool

引數

此函式不接受任何引數。

返回值

如果棧為空,則此函式返回“true”,否則返回“false”。

示例 1

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

<?php    
   $stack = new \Ds\Stack();
   echo "The stack elements are: \n";
   print_r($stack);
   echo "Is stack is empty? ";
   #using isEmpty() function
   var_dump($stack->isEmpty());   
?>

輸出

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

The stack elements are:
Ds\Stack Object
(
)
Is stack is empty? bool(true)

示例 2

如果當前棧不為空,則isEmpty()函式返回“false”:

以下是 PHP Ds\Stack::isEmpty()函式的另一個示例。我們使用此函式來檢查此棧([1, 2, 3])是否為空:

<?php    
   $stack = new \Ds\Stack([1, 2, 3]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "Is stack is empty? ";
   #using isEmpty() function
   var_dump($stack->isEmpty());   
?>

輸出

上述程式產生以下輸出:

The stack elements are:
Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Is stack is empty? bool(false)

示例 3

使用isEmpty()函式的結果在條件語句中檢查當前棧是否為空:

<?php    
   $stack = new \Ds\Stack(["Tutorials", "Point", "India"]);
   echo "The stack elements are: \n";
   print_r($stack);
   #using the isEmpty() function
   $res = $stack->isEmpty();
   if($res){
	   echo "Stack is empty";
   }
   else{
	   echo "Stack is non-empty";
   }
?>

輸出

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

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
Stack is non-empty
php_function_reference.htm
廣告