What is the Ds\Vector remove() function in PHP?
Overview
The Vector class in PHP is an array that is automatically resized. The elements of a Vector instance are accessible via indexes.
This shot discusses the remove method of the Vector class.
The remove method removes an element from the Vector at the specified $index argument and returns the removed element.
Syntax
<?php
public Ds\Vector::remove(int $index): mixed
?>
Parameters
$indexis an integer that specifies the index of theVectorto be removed.
Return value
- The value that is removed is returned.
Exceptions
OutOfRangeExceptionis thrown if the index is not valid (e.g., is not in range).
Example
<?php$vec = new \Ds\Vector(["A", "B", "C"]);print_r("Vector before remove call: ");foreach ($vec as $elem) {print_r($elem." ");}print_r("\n");print_r("Element removed from index 1: ".$vec->remove(1));print_r("\n");print_r("Vector after remove call: ");foreach ($vec as $elem) {print_r($elem." ");}print_r("\n");?>
Output:
Vector before remove call: A B C
Element removed from index 1: B
Vector after remove call: A C
To run this program, you need to install Data Structures for PHP on your local machine.
A new Vector is initialized and stored in the $vec variable in the example above. $vec consists of A, B, and C. The $vec->remove(1) expression invokes the remove method with the $index value of 1 over the $vec variable, resulting in the removal of element B from $vec. Moreover, the remove method call also returns this removed element, B.
Free Resources