PHP - Ds Sequence::pop() 函式



PHP 的 Ds\Sequence::pop() 函式會移除序列中的最後一個值,並將之前移除的值作為結果返回。

如果當前序列為空 ([]),此函式將丟擲“UnderflowException”異常。如果嘗試列印序列,則最後一個元素將被從中移除。

語法

以下是 PHP Ds\Sequence::pop() 函式的語法:

abstract public Ds\Sequence::pop(): mixed

引數

此函式不接受任何引數。

返回值

此函式返回最後一個被移除的值。

示例 1

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

<?php 
   $seq = new \Ds\Vector( [1, 2, 3, 4, 5] );
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The last removed element: ";
   #using pop() function
   print_r($seq->pop());
?>

輸出

以上程式產生以下輸出:

The sequence elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The last removed element: 5

示例 2

使用 for 迴圈中的 pop() 函式逐個彈出所有元素。

以下是 PHP Ds\Sequence::pop() 函式的另一個示例。我們使用此函式從該序列的末尾移除元素(['a', 'e', 'i', 'o', 'u']):

<?php 
   $seq =  new \Ds\Vector(['a', 'e', 'i', 'o', 'u']);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The removed elements are: \n";
   for($i = 0; $i < 5; $i++){ 
      print_r($seq->pop()."\n");
   }
   echo "The sequence after pop each elements: \n";
   print_r($seq);
?>

輸出

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

The sequence elements are:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The removed elements are:
u
o
i
e
a
The sequence after pop each elements:
Ds\Vector Object
(
)

示例 3

如果當前序列為空 ([])pop() 函式將丟擲“UnderflowException”異常:

<?php 
   $seq =  new \Ds\Vector([]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The removed element is: ";
   print_r($seq->pop());
   echo "\nThe sequence after pop last element: \n";
   print_r($seq);
?>

輸出

執行上述程式後,它將丟擲以下異常:

The sequence elements are:
Ds\Vector Object
(
)
The removed element is: PHP Fatal error:  Uncaught UnderflowException: 
Unexpected empty state in C:\Apache24\htdocs\index.php:6
Stack trace:
#0 C:\Apache24\htdocs\index.php(6): Ds\Vector->pop()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 6
php_function_reference.htm
廣告