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
廣告