PHP array slice

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP : array_slice() function

PHP: Extract a slice of the array

The array_slice() function is used to extract a slice of an array.

Version

(PHP 4 and above)

Syntax

array_slice(array_name, starting_position, slice_length, preserve_keys) 

The array_slice() function returns the sequence of elements from the array array as specified by the starting_position and slice_length parameters.

Parameters

Name

Description

Required /
Optional

Type

Type

array_name

Array name.

Required

Array

starting_position

Specifies the beginning position of the slice in the array.

Required

Integer

slice_length

Length of the slice.

Optional

Integer

preserve_keys

Specify TRUE or FALSE, whether the function shall preserve the array's keys or not. The default value is FALSE.

Optional

Boolean

Return value

The slice.

Value Type : Array

Pictorial Presentation :

php array array_slice() function

Example :

  1. $fruits_list = array('Orange','Apple','Banana','Cherry');  

  2. $result= array_slice($fruits_list,3);  

  3. print_r($result);  

  4. echo "
    ";  

  5. $result= array_slice($fruits_list,-2,1);  

  6. print_r($result);  

  7. echo "
    ";  

  8. $result= array_slice($fruits_list,0,4);  

  9. print_r($result);  

  10. ?>  

Output :

Array ( [0] => Cherry )
Array ( [0] => Banana )
Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Cherry )