PHP - Ds Sequence::get() 函式



PHP 的 Ds\Sequence::get() 函式用於在序列中檢索指定索引處的值。“索引”表示序列中元素的位置,從 0 開始。這意味著索引值 0 表示第一個元素,1 表示第二個元素,依此類推。

如果指定的索引無效(即為負數或大於序列大小),則會丟擲“OutOfRangeException”異常。

語法

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

public abstract mixed Ds\Sequence::get( int $index )

引數

此函式接受一個名為“index”的引數,如下所述:

  • index - 從 0 開始的索引,在其中搜索值。

返回值

此函式返回指定索引處的值。

示例 1

以下程式演示了 PHP Ds\Sequence::get() 函式的使用:

<?php 
   $seq = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The sequence elements are: \n";
   print_r($seq);
   $index = 0;
   echo "The index is: ".$index;
   echo "\nThe value at index ".$index." is: ";
   #using get() function
   print_r($seq->get($index));
?>

輸出

以上程式產生以下輸出:

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

示例 2

以下是 PHP Ds\Sequence::get() 函式的另一個示例。我們使用此函式在此序列(["Tutorials", "Point", "Tutorix", "India"])中檢索指定索引 2 處的值:

<?php 
   $seq = new \Ds\Vector(["Tutorials", "Point", "Tutorix", "India"]);
   echo "The sequence elements are: \n";
   print_r($seq);
   $index = 2;
   echo "The index is: ".$index;
   echo "\nThe value at index ".$index." is: ";
   #using get() function
   print_r($seq->get($index));
?>

輸出

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

The sequence elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Tutorix
    [3] => India
)
The index is: 2
The value at index 2 is: Tutorix

示例 3

如果指定的索引值無效,則此函式會丟擲“OutOfRangeException”異常。

<?php 
   $seq = new \Ds\Vector(['a', 'e', 'i', 'o', 'u']);
   echo "The sequence elements are: \n";
   print_r($seq);
   $index = -1;
   echo "The index is: ".$index;
   echo "\nThe value at index ".$index." is: ";
   #using get() function
   print_r($seq->get($index));
?>

輸出

以上程式丟擲以下異常:

The sequence elements are:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The index is: -1
The value at index -1 is: PHP Fatal error:  Uncaught OutOfRangeException: 
Index out of range: -1, expected 0 <= x <= 4 in C:\Apache24\htdocs\index.php:9
Stack trace:
#0 C:\Apache24\htdocs\index.php(9): Ds\Vector->get(-1)
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 9
php_function_reference.htm
廣告