HomeLanguagesPHP | DsSequence slice() Function

PHP | Ds\Sequence slice() Function

The Ds\Sequence::slice() function is an inbuilt function in PHP which is used to return the subsequence of given range.

Syntax:

Ds\Sequence abstract public Ds\Sequence::slice ( int $index 
[, int $length ] )

Parameters: This function accepts two parameters as mentioned above and described below:

  • $index: This parameter hold the starting index of subsequence. The index value can be positive and negative. If the index value is positive then it starts at the index of sequence and if the index value is negative then it sequence starts from ends.
  • $length: This parameter holds the length of subsequence. This parameter can take positive and negative values. If length is positive then subsequence size is equal to a given length and if the length is negative then the sequence will stop that many values from the end.

Return value: This function returns the subsequence of given range.

Below programs illustrate the Ds\Sequence::slice() function in PHP:

Program 1:




<?php
   
// Create new sequence
$seq =  new \Ds\Vector([1, 3, 6, 9, 10, 15, 20]);
  
// Use slice() function to create 
// sub sequence and display it
print_r($seq->slice(2));
  
print_r($seq->slice(1, 2));
  
print_r($seq->slice(2, -2));
  
?>


Output:

Ds\Vector Object
(
    [0] => 6
    [1] => 9
    [2] => 10
    [3] => 15
    [4] => 20
)
Ds\Vector Object
(
    [0] => 3
    [1] => 6
)
Ds\Vector Object
(
    [0] => 6
    [1] => 9
    [2] => 10
)

Program 2:




<?php
   
// Create new sequence
$seq =  new \Ds\Vector(["Geeks", "GFG", "Abc", "for"]);
  
// Use slice() function to create 
// sub sequence and display it
print_r($seq->slice(3));
  
print_r($seq->slice(2, 0));
  
print_r($seq->slice(0, 3));
  
?>


Output:

Ds\Vector Object
(
    [0] => for
)
Ds\Vector Object
(
)
Ds\Vector Object
(
    [0] => Geeks
    [1] => GFG
    [2] => Abc
)

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

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS