Current Location: Home> Latest Articles> The effect of the preserve_keys parameter in array_slice on key name retention

The effect of the preserve_keys parameter in array_slice on key name retention

gitbox 2025-05-28

In PHP, the array_slice function is a very practical tool to intercept the specified parts of an array. Its function signature is as follows:

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

Among them, the parameter $preserve_keys is used to control whether to retain the key name of the original array. The function of this parameter seems simple, but in actual use, many people have doubts about whether it really retains the key name. This article will explain the behavior of the $preserve_keys parameter in detail and explain it in conjunction with code examples.

The function of the $preserve_keys parameter

array_slice will intercept a piece of data from the array $array . By default (that is, $preserve_keys is false ), the returned array will be reindexed, that is, the key name will be reset to a number index starting from 0.

When $preserve_keys is set to true , the function will try to preserve the key name of the original array. This is very important when dealing with associative arrays, because you want to preserve the meaning of the key name.

Sample code analysis

Let's use a piece of code to illustrate:

 <?php
$array = [
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry',
    5   => 'date',
    6   => 'elderberry',
];

// Default behavior preserve_keys = false
$slice1 = array_slice($array, 1, 3);
print_r($slice1);

/*
Output:
Array
(
    [0] => banana
    [1] => cherry
    [2] => date
)
*/

// preserve_keys = true
$slice2 = array_slice($array, 1, 3, true);
print_r($slice2);

/*
Output:
Array
(
    [b] => banana
    [c] => cherry
    [5] => date
)
*/
?>

From the above code, we can see:

  • When $preserve_keys is false , the returned array key name is reset to the numeric index (0, 1, 2).

  • When $preserve_keys is true , the return array retains the original key names 'b' , 'c' and 5 .

Things to note

  • If the array is an index array (numeric key), and $preserve_keys is false , the returned array key name will be rearranged.

  • If it is an associative array (string key), even if $preserve_keys is false , the key name will be replaced with a numeric index, which will cause the key name to be lost.

  • When $preserve_keys is true , the returned array key name remains the same, but if you use this array for subsequent operations, be sure to pay attention to the integrity of the key name.

Additional supplements

Description of array_slice in the official manual: https://gitbox.net/manual/en/function.array-slice.php

The domain name is replaced here as gitbox.net , you can visit for more details.