Open In App

PHP | Ds\Vector slice() Function

The Ds\Vector::slice() function is an inbuilt function in PHP which is used to return the sub-vector of the given vector.

Syntax:



Ds\Vector public Ds\Vector::slice( $index, $length )/pre>

Parameters: This function accepts two parameter as mentioned above and described below:
Return Value: This function returns a sub-vector of given range. Below programs illustrate the Ds\Vector::slice() function in PHP: Program 1:
<?php
  
// Create new vector
$vect = new \Ds\Vector([1, 2, 3, 4, 5, 6]);
  
echo("Original vector:\n");
  
// Display the vector element
var_dump($vect);
  
// Use slice() function to 
// create sub vector
$res = $vect->slice(1, 2);
  
echo("\nNew sub-vector\n");
  
// Display the sub-vector elements
var_dump($res);
  
?>

Output:

Original vector:
object(Ds\Vector)#1 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}

New sub-vector
object(Ds\Vector)#2 (2) {
  [0]=>
  int(2)
  [1]=>
  int(3)
}

Program 2:




<?php
  
// Create new vector
$vect = new \Ds\Vector([1, 2, 3, 4, 5, 6]);
  
echo("Original vector:\n");
  
// Display the vector element
var_dump($vect);
  
// Use slice() function to 
// create sub vector
$res = $vect->slice(2, -2);
  
echo("\nNew sub-vector\n");
  
// Display the sub-vector elements
var_dump($res);
  
$res = $vect->slice(4);
  
echo("\nNew sub-vector\n");
  
// Display the sub-vector elements
var_dump($res);
  
?>

Output:



Original vector:
object(Ds\Vector)#1 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}

New sub-vector
object(Ds\Vector)#2 (2) {
  [0]=>
  int(3)
  [1]=>
  int(4)
}

New sub-vector
object(Ds\Vector)#3 (2) {
  [0]=>
  int(5)
  [1]=>
  int(6)
}

Reference: http://php.net/manual/en/ds-vector.slice.php


Article Tags :