PHP - Ds Vector::set() 函数



PHP 的 Ds\Vector::set() 函数用于使用指定值更新向量中给定索引处的现有值。

如果指定的索引值无效,此函数将抛出“OutOfRangeException”异常。无效索引可以为负数或超过向量的长度。

语法

以下是 PHP Ds\Vector::set() 函数的语法:

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

参数

以下是此函数的参数:

  • $index - 要更新的值的索引。
  • $value - 将替换现有值的新值。

返回值

此函数不返回值。

示例 1

以下是 PHP Ds\Vector::set() 函数的基本示例:

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo "The original vector: \n";   
   print_r($vector);
   $index = 1;
   $value = 10;
   echo "The index is: ".$index;
   echo "\nThe given value is: ".$value;
   #using vector() function
   $vector->set($index, $value);
   echo("\nThe vector after updating an element: \n"); 
   print_r($vector); 
?>

输出

上述程序产生以下输出:

The original vector:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The index is: 1
The given value is: 10
The vector after updating an element:
Ds\Vector Object
(
    [0] => 1
    [1] => 10
    [2] => 3
    [3] => 4
    [4] => 5
)

示例 2

以下是 PHP Ds\Vector::set() 函数的另一个示例。我们使用此函数更新此向量(["Tutorials", "Point", "India"]) 指定索引“2”处的现有值:

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The original vector: \n";   
   print_r($vector);
   $index = 2;
   $value = "Tutorix";
   echo "The index is: ".$index;
   echo "\nThe given value: ".$value;
   #using set() function
   $vector->set($index, $value);
   echo("\nThe vector after updating an element: \n"); 
   print_r($vector); 
?>

输出

执行上述程序后,将显示以下输出:

The original vector:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The index is: 2
The given value: Tutorix
The vector after updating an element:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Tutorix
)

示例 3

如果给定的索引无效set() 函数将抛出“OutOfRangeException”异常:

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

输出

执行上述程序后,将生成以下输出:

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