Monday, October 6, 2025
HomeLanguagesPHP | DsDeque slice() Function

PHP | Ds\Deque slice() Function

The Ds\Deque::slice() function is an inbuilt function in PHP which is used to return a sub-Deque which contains elements of the Deque within the index range.

Syntax:

public Ds\Deque::slice( $index, $length ) : Ds\Deque

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

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

Return Value: This function returns a sub-Deque with sliced elements from the Deque of given range.

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

Program 1:




<?php
  
// Declare a deque
$deck = new \Ds\Deque([1, 2, 3, 4, 5, 6]);
  
echo("Elements of Deque\n");
  
// Display the Deque elements
print_r($deck);
  
// Slicing deque from 2 to 5
$deck_new = $deck->slice(2, 5);
   
echo("\nDeque after slicing:\n");
  
// Display the Deque elements
print_r($deck_new);
  
?>


Output:

Elements of Deque
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

Deque after slicing:
Ds\Deque Object
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 6
)

Program 2:




<?php
  
// Declare a deque
$deck = new \Ds\Deque([1, 2, 3, 4, 5, 6]);
  
echo("Elements of Deque\n");
  
// Display the Deque elements
print_r($deck);
  
// Slicing deque from 3 to -2
$deck_new = $deck->slice(3, -2);
   
echo("\nDeque after slicing:\n");
  
// Display the Deque elements
print_r($deck_new);
  
?>


Output:

Elements of Deque
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

Deque after slicing:
Ds\Deque Object
(
    [0] => 4
)

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32338 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6825 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6781 POSTS0 COMMENTS