Skip to content
Related Articles

Related Articles

Improve Article

PHP | Ds\Vector slice() Function

  • Last Updated : 22 Aug, 2019

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:
  • $index: This parameter hold the starting index of sub-vector. The index value can be positive and negative. If the index value is positive then it starts at the index of vector and if the index value is negative then it starts from ends.
  • $length: This parameter holds the length of sub-vector. This parameter can take positive and negative values. If length is positive then sub-vector size is equal to a given length and if the length is negative then vector will stop that many values from the end.
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




My Personal Notes arrow_drop_up
Recommended Articles
Page :