PHP - Ds Vector::remove() 函数



PHP 的 Ds\Vector::remove() 函数用于移除向量中指定索引处的某个值,并返回结果中被移除的元素。

如果索引无效(即索引值“小于零”或“大于等于”向量大小),此函数将抛出 OutOfRangeException 异常。

语法

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

public Ds\Vector::remove(int $index): mixed

参数

此函数接受一个名为“index”的参数,其描述如下:

  • $index − 要移除的值的索引。

返回值

此函数返回被移除的值。

示例 1

以下程序演示了 PHP Ds\Vector::remove() 函数的使用:

<?php
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo("The vector elements are: \n"); 
   print_r($vector);
   $index = 0;
   echo "The index value is: ".$index;
   echo "\nThe element removed at index ".$index." is: ";
   print_r($vector->remove($index));   
?>

输出

以上程序输出如下:

The vector elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The index value is: 0
The element removed at index 0 is: 1

示例 2

以下是 PHP Ds\Vector::remove() 函数的另一个示例。我们使用此函数来移除并检索此向量(["Tutorials", "Point", "Tutorix"]) 指定索引 2 处的元素:

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "Tutorix"]);
   echo("The vector elements are: \n");
   print_r($vector);
   $index = 2;
   echo "The index is: ".$index;
   echo "\nThe removed element: \n";
   #using remove() function
   print_r($vector->remove($index));
   echo "\nThe updated vector: \n";
   print_r($vector);
?>

输出

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Tutorix
)
The index is: 2
The removed element:
Tutorix
The updated vector:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
)

示例 3

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

<?php 
   $vector = new \Ds\Vector(['a', 'e', 'i', 'o', 'u']);
   echo("The vector elements are: \n");
   print_r($vector);
   $index = -1;
   echo "The index is: ".$index;
   echo "\nThe removed element: \n";
   #using remove() function
   print_r($vector->remove($index));
   echo "\nThe updated vector: \n";
   print_r($vector);
?>

输出

执行以上程序后,将抛出以下异常:

The vector elements are:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The index is: -1
The removed element:
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->remove(-1)
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 9
php_function_reference.htm
广告