PHP array_slice()Functions

PHP Array ReferenceComplete PHP Array Reference

Examples

Extract starting from the third element of the array (index 2), and return all elements up to the end of the array:

<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2)); ?>

Run example »

Definition and Usage

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

Note:If the array has string keys, the returned array will preserve the keys (see Example 4).


Syntax

array_slice(array,start,length,preserve)

Parameter Description
array Required. Specifies the array.
start Required. A number. Specifies the starting position of the elements to extract. 0 = the first element. If this value is set to a positive number, extraction starts from the beginning. If this value is set to a negative number, extraction starts from the absolute value of start counting from the end. -2 means starting from the second-to-last element of the array.
length Optional. A number. Specifies the length of the returned array. If this value is set to an integer, that number of elements is returned. If this value is set to a negative number, the function stops extracting this far from the end of the array. If this value is not set, all elements from the position set by the start parameter to the end of the array are returned.
preserve Optional. Specifies whether the function preserves or resets the keys. Possible values:
  • true - Preserve keys
  • false - Default. Reset keys

Technical Details

Return value: Returns the selected part of the array.
PHP Version: 4+
Changelog: preserveThe parameter was added in PHP 5.0.2.


More Examples

Example 1

Extract starting from the second element of the array, and return two elements:

<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,1,2)); ?>

Run example »

Example 2

Using a negative start parameter:

<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,-2,1)); ?>

Run example »

Example 3

With the preserve parameter set to true:

<?php //preserve set to true, keys are preserved $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,1,2,true)); //preserve set to false (default), keys are not preserved $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,1,2,false)); //Note that the keys of the two arrays are different ?>

Run example »

Example 4

With string and integer keys:

<?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"brown"); print_r(array_slice($a,1,2)); $a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"brown"); print_r(array_slice($a,1,2)); ?>

Run example »


PHP Array ReferenceComplete PHP Array Reference Other Extensions