w3resource

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
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

Example:

<?php
$fruits_list = array('Orange','Apple','Banana','Cherry');
$result= array_slice($fruits_list,3);
print_r($result);
echo "<br>";
$result= array_slice($fruits_list,-2,1);
print_r($result);
echo "</br>";
$result= array_slice($fruits_list,0,4);
print_r($result);
?>

Output:

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

Pictorial Presentation:

php function reference: array_slice() function

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: array_shift
Next: array_sum



PHP: Tips of the Day

PHP: Extract numbers from a string

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);