PHP - Ds Sequence::shift() 函式



PHP 的 Ds\Sequence::shift() 函式用於移除並檢索序列中的第一個值。Ds\Sequence 類提供了另一個名為 remove() 的函式,該函式移除指定索引處的元素,如果索引為 0,則移除第一個值。

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

語法

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

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

引數

此函式不接受任何引數。

返回值

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

示例 1

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

<?php 
   $seq = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The deleted element: ";
   #using shift() function
   print_r($seq->shift());
?>

輸出

上述程式產生以下輸出:

The sequence elements are:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The deleted element: 10

示例 2

以下是 PHP Ds\Sequence::shift() 函式的另一個示例。我們使用此函式移除並檢索此序列 (["Raja", "Jai", "Adithya"]) 的第一個元素:

<?php 
   $seq = new \Ds\Vector(["Raja", "Jai", "Adithya"]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The deleted elements are: ";
   for($i = 0; $i<3; $i++){
	   print_r($seq->shift()." ");
   }
   echo "\nThe sequence after shift: \n";
   print_r($seq);
?>

輸出

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

The original sequence:
Ds\Vector Object
(
    [0] => Raja
    [1] => Jai
    [2] => Adithya
)
The deleted elements are: Raja Jai Adithya
The sequence after shift:
Ds\Vector Object
(
)

示例 3

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

<?php 
   $seq = new \Ds\Vector([]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The deleted elements are: ";
   print_r($seq->shift());
   echo "\nThe sequence after shift: \n";
   print_r($seq);   
?>

輸出

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

The original sequence:
Ds\Vector Object
(
)
The deleted elements are: 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->shift()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 6
php_function_reference.htm
廣告