PHP - Ds Sequence::remove() 函数



PHP 的 Ds\Sequence::remove() 函数从序列中移除指定索引处的数值,并返回移除的数值。

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

语法

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

public abstract mixed Ds\Sequence::remove( int $index )

参数

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

  • index - 将要移除元素的位置。

返回值

此函数返回已移除的数值。

示例 1

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

<?php 
   $seq = new \Ds\Vector([10, 20, 30]);
   echo "The sequence elements are: \n";
   print_r($seq); 
   $index = 0;
   echo "The index value is: ".$index;
   echo "\nThe removed value is: ";
   #using remove() function
   print_r($seq->remove($index));
?>

输出

上述程序产生以下输出:

The sequence elements are:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
)
The index value is: 0
The removed value is: 10

示例 2

以下是 PHP Ds\Sequence::remove() 函数的另一个示例。我们使用此函数从该序列(['a', 'e', 'i', 'o', 'u'])中移除指定索引3处的元素:

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

输出

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

The sequence elements are:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The index value is: 3
The removed value is: o
The sequence after remove:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => u
)

示例 3

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

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

输出

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

The sequence elements are:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The index value is: -1
The removed value is: 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
广告