141 of 410 menu

The array_slice Function

The array_slice function slices and returns a part of an array. The original array remains unchanged. The first parameter specifies the array to be sliced. The second parameter specifies from which element to start slicing, and the third - how many elements to slice. The second parameter can be negative - in this case the count will start from the end (-1 - the last element, -2 - the second to last, and so on). The third parameter can be omitted entirely - in this case the array will be sliced to the very end.

The last optional parameter controls whether to preserve keys when slicing, true - preserve, false (default) - do not preserve. String keys are always preserved, regardless of the value of this parameter.

Syntax

array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

Example

Let's extract elements starting from the first (has index 0), 3 pieces:

<?php $arr = ['a', 'b', 'c', 'd', 'e']; $res = array_slice($arr, 0, 3); var_dump($res); ?>

Code execution result:

['a', 'b', 'c']

Example

Let's extract elements starting from the second (has index 1), 3 pieces:

<?php $arr = ['a', 'b', 'c', 'd', 'e']; $res = array_slice($arr, 1, 3); var_dump($res); ?>

Code execution result:

['b', 'c', 'd']

Example

Let's extract elements starting from the second (has index 1) to the end of the array. For this, the third parameter is omitted:

<?php $arr = ['a', 'b', 'c', 'd', 'e']; $res = array_slice($arr, 1); var_dump($res); ?>

Code execution result:

['b', 'c', 'd', 'e']

Example

Let's extract elements starting from the second to last, 2 pieces. For this, the second parameter is set to -2 (the position of the second to last element):

<?php $arr = ['a', 'b', 'c', 'd', 'e']; $res = array_slice($arr, -2, 2); var_dump($res); ?>

Code execution result:

['d', 'e']

Example

By default, the array does not preserve keys when slicing:

<?php $arr = [1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'c']; $res = array_slice($arr, 0, 3); var_dump($res); ?>

Code execution result:

['a', 'b', 'c']

Example

Let's make it so that the keys are preserved. For this, set the last parameter to true:

<?php $arr = [1 => 'a', 2 => 'b', 3 => 'c']; $res = array_slice($arr, 0, 3, true); var_dump($res); ?>

Code execution result:

[1 => 'a', 2 => 'b', 3 => 'c']

Example

String keys are preserved when slicing:

<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; $res = array_slice($arr, 0, 3); var_dump($res); ?>

Code execution result:

['a' => 1, 'b' => 2, 'c' => 3]

See Also

  • the array_splice function,
    which slices a part of an array, changing the original array in the process
byenru