PHP - Ds Set get() 函式



PHP 的 Ds\Set::get() 函式用於檢索當前集合中指定索引處的值。索引從位置 0 開始,因此索引 0 表示第一個元素,索引 1 表示第二個元素,依此類推。

如果指定的索引值是負數或無效(不在範圍內),則此函式將丟擲“OutOfRangeException”異常。

語法

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

public mixed Ds\Set::get( int $index )

引數

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

  • index - 指定要訪問的索引的整數值。

返回值

此函式返回請求索引處的值。

示例 1

以下是 PHP Ds\Set::get() 函式的基本示例。

<?php
   $set = new \Ds\Set([132, 312, 213, 123, 231]);
   echo "The set elements are: \n";
   print_r($set);
   $index = 3;
   echo "The index value is: ".$index;
   echo "\nThe elements ".$set->get($index). " is found at index position ".$index;
?>

輸出

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

The set elements are:
Ds\Set Object
(
    [0] => 132
    [1] => 312
    [2] => 213
    [3] => 123
    [4] => 231
)
The index value is: 3
The elements 123 is found at index position 3

示例 2

以下是 PHP Ds\Set::get() 函式的另一個示例。我們使用此函式從此集合(["Welcome", "to", "Tutorials", "point"])中檢索指定索引 0 處的元素。

<?php
    $set = new \Ds\Set(["Welcome", "to", "Tutorials", "point"]);
    echo "The set elements are: \n";
    print_r($set);
	$index = 0;
	echo "The index value is: ".$index;
    echo "\nThe elements '".$set->get($index)."' is found at index position ".$index;
?>

輸出

上述程式返回以下輸出:

The set elements are:
Ds\Set Object
(
    [0] => Welcome
    [1] => to
    [2] => Tutorials
    [3] => point
)
The index value is: 0
The elements 'Welcome' is found at index position 0

示例 3

如果 index 引數值為負大於集合大小,則get() 函式將丟擲“OutOfRangeException”異常。

<?php
   $set = new \Ds\Set([10, 20, 30, 40, 50]);
   echo "The set elements are: \n";
   print_r($set);
   $index = 7;
   echo "The index value is: ".$index;
   echo "The element obtained: ";
   var_dump($set->get(7));
?>

輸出

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

The set elements are:
Ds\Set Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The index value is: 7The element obtained: PHP Fatal error: 
Uncaught OutOfRangeException: Index out of range: 7, expected 0 <= x <= 4 in C:\Apache24\htdocs\index.php:8
Stack trace:
#0 C:\Apache24\htdocs\index.php(8): Ds\Set->get(7)
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 8
php_function_reference.htm
廣告