PHP Tutorial - PHP array_slice() Function






Definition

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

Syntax

PHP array_slice() Function has the following syntax.

array_slice(array,start,length,preserve)

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to slice
startRequired.Starting point. 0 = the first element. negative value mean to slice from last element. -2 means start at the second last element of the array.
lengthOptional.length of the returned array. negative number means stop slicing that far from the last element. If not set, the function will return all elements, starting from start.
preserveOptional.preserve or reset the keys.

Possible values for preserve:

  • true - Preserve keys
  • false - Default. Reset keys




Example 1


<?php
    $a=array("A","B","C","D","java2s.com");
    print_r(array_slice($a,2));
?>

The code above generates the following result.

Example 2

Start the slice from from the second array element, and return only two elements:


<?php
    $a=array("A","B","C","D","java2s.com");
    print_r(array_slice($a,1,2));
?>

The code above generates the following result.





Example 3

Using a negative start parameter:


<?php
    $a=array("A","B","C","D","java2s.com");
    print_r(array_slice($a,-2,1));
?>

The code above generates the following result.

Example 4

With the preserve parameter set to true:


<?php
    $a=array("A","B","C","D","java2s.com");
    print_r(array_slice($a,1,2,true));
?>

The code above generates the following result.

Example 5

With both string and integer keys:


<?php
    $a=array("a"=>"Java","b"=>"PHP","c"=>"java2s.com","d"=>"HTML","e"=>"java2s.com");
    print_r(array_slice($a,1,2));
    
    $a=array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"java2s.com");
    print_r(array_slice($a,1,2));
?>

The code above generates the following result.