PHP - Extracting a Range of Elements with array_slice()

Introduction

PHP array_slice() can extract a range of elements from an array.

To use it, pass it the array to extract the slice from, followed by the position of the first element in the range counting from zero, followed by the number of elements to extract.

The function returns a new array containing copies of the elements you extracted and it doesn't touch the original array.

For example:

Demo

<?php

$authors = array("A","B","C","D");
$authorsSlice = array_slice($authors, 1, 2);

// Displays"Array ([0] =>  B [1] => C)"
print_r($authorsSlice);//from w ww . j a v a  2  s.c o m
?>

Result

This example extracts the second and third elements from the $authors array and stores the resulting array in a new variable, $authorsSlice.

The code then uses print_r() to display the slice.

array_slice() doesn't preserve the keys of the original elements, but instead re-indexes the elements in the new array, starting from zero.

So whereas "B" has an index of 1 in the $authors array, it has an index of 0 in the $authorsSlice array.

You can use array_slice() with associative arrays.

Although associative arrays don't have numeric indices, PHP does remember the order of the elements in an associative array.

So you can tell array_slice() to extract, the second and third elements of an associative array:

Demo

<?php

         $myBook = array("title " => "Java",
                        "author" => "John A",
                        "pubYear" =>  2018);
         $myBookSlice = array_slice($myBook, 1, 2);

         // Displays"Array ([author] =>  John A [pubYear] =>  2018)";
         print_r($myBookSlice);/* w w  w. j  a v a2s  . co m*/
?>

Result

array_slice() does preserve the keys of elements from an associative array.

If you leave out the third argument to array_slice(), the function extracts all elements from the start position to the end of the array:

Demo

<?php

         $authors = array("A","B","C","D");
         $authorsSlice = array_slice($authors, 1);

         // Displays"Array ([0] =>  B [1] =>  C [2] =>  D)";
         print_r($authorsSlice);/*from  w  ww . j av  a  2  s  . c o  m*/
?>

Result

To preserve the indices in indexed array, pass a fourth argument, true, to array_slice() :

Demo

<?php

         $authors = array("A","B","C","D");

         // Displays"Array ([0] =>  C [1] =>  D)";
         print_r(array_slice($authors, 2, 2));

         // Displays"Array ([2] =>  C [3] =>  D)";
         print_r(array_slice($authors, 2, 2, true));
?>/* w  w  w .  j  av  a 2s  .c o  m*/

Result

Related Topic