array_slice() function in PHP


The array_slice() function returns selected parts of an array.

Syntax

array_slice(arr, begin, length, preserve)

Parameters

  • arr − The specified array

  • begin − The beginning of the array where the slicing will take place. It shows the position in the array. If begin is negative (-1), then the slicing begins from the end of the array. The value -2 means begin at the second last element of the array.

  • length − The length of the returned array. If the length is negative then the slicing will stop that many elements from the end of the array.

  • preserve − Possible values are TRUE or FALSE. Here, set whether the keys are to be preserved (TRUE) or resert (FALSE).

Return

The array_slice() function returns the selected part of an array.

Example

The following is an example −

 Live Demo

<?php
$arr = array("laptop","mobile","tablet","pendrive","headphone");
print_r(array_slice($arr,2,3, true));
?>

Output

The following is the output −

Array
(
[2] => tablet
[3] => pendrive
[4] => headphone
)

Example

Let us see another example −

 Live Demo

<?php
$arr = array("electronics","accessories","shoes","toys","bags");
print_r(array_slice($arr,1,3, false));
?>

Output

The following is the output −

Array
(
[0] => accessories
[1] => shoes
[2] => toys
)

Example

Let us see another example −

 Live Demo

<?php
$arr = array("one","two","three","four");
print_r(array_slice($arr,-2));
?>

Output

The following is the output −

Array
(
[0] => three
[1] => four
)

Updated on: 23-Dec-2019

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements