1// array_slice($array, $offset, $length)
2
3$array = array(1,2,3,4,5,6);
4
5// positive $offset: an offset from the begining of array
6print_r(array_slice($array, 2)); // [3,4,5,6]
7
8// negative $offset: an offset from the end of array
9print_r(array_slice($array, -2)); // [5,6]
10
11// positive $length: the slicing will stop $length elements
12// from offset
13print_r(array_slice($array, 2, 3)); // [3,4,5]
14
15// negative $length: the slicing will stop $length elements
16// from the end of array
17print_r(array_slice($array, 2, -3)); // [3]
1array_slice() function is used to get selected part of an array.
2Syntax:
3array_slice(array, start, length, preserve)
4*preserve = false (default)
5If we put preserve=true then the key of value are same as original array.
6
7Example (without preserve):
8<?php
9$a=array("red","green","blue","yellow","brown");
10print_r(array_slice($a,1,2));
11?>
12
13Output:
14Array ( [0] => green [1] => blue )
15
16Example (with preserve):
17<?php
18$a=array("red","green","blue","yellow","brown");
19print_r(array_slice($a,1,2,true));
20?>
21
22Output:
23Array ( [1] => green [2] => blue )
24
1PHP function array_slice(array $array, int $offset, ?int $length, bool $preserve_keys = false) string[]
2---------------------------------------------------------------------------------------------------
3Extract a slice of the array.
4
5Parameters:
6array--$array--The input array.
7int--$offset--If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.
8int|null--$length--[optional]--If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
9bool--$preserve_keys--[optional]--Note that array_slice will reorder and reset the array indices by default. You can change this behaviour by setting preserve_keys to true.
10
11Returns: the slice.