In this tutorial, you shall learn how to preserve keys while slicing an array in PHP using array_slice() function, with example programs.

PHP – Preserve keys while slicing array

To preserve keys when slicing an array in PHP using array_slice() function, pass true for the  $preserve_keys parameter.

The syntax of array_slice() function is

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

Example

In the following program, we take an array $arr, and slice it from an offset index of 2 till the end of the array using array_slice() function, and preserve the keys by passing a value of true for the $preserve_keys parameter.

PHP Program

<?php
$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g');
$offset = 2;

$sliced_array = array_slice($array, $offset, null , true);
print_r($sliced_array);
?>

Output

PHP - Preserve keys while slicing array
ADVERTISEMENT

Conclusion

In this PHP Tutorial, we learned how to preserve keys while slicing an array using array_slice() function.