PHP - Ds Sequence::insert() 函数



PHP 的 Ds\Sequence::insert() 函数用于在序列的给定索引处插入值。“索引”是序列中元素的位置,从 0 开始,代表第一个元素,1 代表第二个元素,以此类推。

如果指定的索引“无效”(即负数或大于序列大小),此函数将抛出“OutOfRangeException”异常。

语法

以下是 PHP Ds\Sequence::insert() 函数的语法:

abstract public Ds\Sequence::insert(int $index, mixed ...$values): void

参数

以下是此函数的参数:

  • index - 需要插入值的索引。
  • values - 要插入的一个或多个值。

返回值

此函数不返回值。

示例 1

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

<?php
   $seq = new \Ds\Vector([2, 3, 4, 5]);
   echo "The original sequence: \n";
   print_r($seq);
   $index = 0;
   $val = 1;
   echo "The given index is: ".$index;
   echo "\nThe given value is: ".$val;
   echo "\nThe sequence after insert: \n";
   #using insert() function
   $seq->insert($index, $val);
   print_r($seq);
?>

输出

以上程序输出如下:

The original sequence:
Ds\Vector Object
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
)
The given index is: 0
The given value is: 1
The sequence after insert:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

示例 2

以下是 PHP Ds\Sequence::insert() 函数的另一个示例。我们使用此函数在此序列 ([]) 中指定索引处插入值:

<?php
   $seq = new \Ds\Vector([]);
   echo "The original sequence: \n";
   print_r($seq);
   $count = 0;
   for($i = 0; $i<=10; $i++){
	   $count += 1;
	   #using insert() function
	   $seq->insert($i, $count);
   }
   echo "The sequence after insert: \n";
   print_r($seq);
?>

输出

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

The original sequence:
Ds\Vector Object
(
)
The sequence after insert:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
)

示例 3

如果给定的索引无效(即负数),insert() 函数将抛出“OutOfRangeException”异常,如下所示:

<?php
   $seq = new \Ds\Vector(['a', 'b', 'c']);
   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 sequence after insert: \n";
   #using insert() function
   $seq->insert($index, $val);
   print_r($seq);
?>

输出

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

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