PHP - Ds Sequence::set() 函式



PHP 的 Ds\Sequence::set() 函式用於更新給定索引處的數值。索引是序列中元素的位置,從 0 開始,表示第一個元素,1 表示第二個元素,以此類推。

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

語法

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

public abstract void Ds\Sequence::set( int $index , mixed $value )

引數

以下是此函式的引數:

  • index - 要更新的值的基於 0 的索引。
  • value - 要替換成的新的值。

返回值

此函式不返回任何值。

示例 1

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

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

輸出

以下是上述程式的輸出:

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

示例 2

以下是 PHP Ds\Sequence::set() 函式的另一個示例。我們使用此函式在該序列 (["Tutorials", "Point", "India"]) 中的索引 2 處將現有值更新為 "Hyderabad":

<?php
   $seq = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The original sequence: \n";
   print_r($seq);
   $index = 2;
   $val = "Hyderabad";
   echo "The given index is: ".$index;
   echo "\nThe given value is: ".$val;
   echo "\nThe updated sequence: \n";
   #using set() function
   $seq->set($index, $val);
   print_r($seq);
?>

輸出

上述程式產生以下輸出:

The original sequence:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The given index is: 2
The given value is: Hyderabad
The updated sequence:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Hyderabad
)

示例 3

如果指定的索引 無效(即為負數),set() 函式將丟擲“OutOfRangeException”異常:

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

輸出

執行上述程式後,將顯示以下內容:

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