Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_slice()

Example

Start the slice from the third element of the array and return the remaining elements.

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

Definition and Usage

The array_slice() function returns a portion of an array.

 

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

Syntax

array_slice(array, start, length, preserve)

Parameter Values

 

Parameter

Description

array

Required. Specifies the array to slice.

start

Required. Numeric value. Specifies the starting point for the slice. 0 refers to the first element. If set to a negative number, the slice will start that many positions from the end of the array. For example, -2 means start at the second-to-last element.

length

Optional. Numeric value. Specifies the length of the returned array. If set to a negative number, the function will stop slicing that many positions from the end of the array. If this value is not provided, the function will return all elements starting from the position specified by the start parameter.

preserve

Optional. Specifies whether the function should preserve or reset the keys. Possible values are:

·         true – Preserve keys

·         false (default) – Reset keys

Technical Details

Return Value:

Returns a subset of an array.

PHP Version:

4+

PHP Changelog:

The preserve parameter was introduced in PHP 5.0.2.

More Examples

Example 1

Start the slice from the second element of the array and return only two elements.

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

Example 2

Using a negative start parameter:

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

Example 3

With the preserve parameter set to true:

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

Example 4

With both 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));
?>