Current Location: Home> Latest Articles> How to avoid key name loss when using array_slice

How to avoid key name loss when using array_slice

gitbox 2025-05-26

In PHP, array_slice() is a commonly used array processing function, mainly used to extract elements of a specified range from an array. However, many developers often encounter a problem when using array_slice() : the key names in the original array will be reset to an integer index starting from 0 after slice. This is especially troublesome when dealing with associative arrays, as key names may have important semantic or structural meanings.

This article will introduce in detail how to avoid key name loss when using array_slice() and provide practical example code to help understand.

Question example

 $users = [
    'alice' => 'Alice Smith',
    'bob' => 'Bob Johnson',
    'carol' => 'Carol King',
    'dave' => 'Dave Lee'
];

$sliced = array_slice($users, 1, 2);
print_r($sliced);

Running results:

 Array
(
    [0] => Bob Johnson
    [1] => Carol King
)

As shown above, both 'bob' and 'carol' key names are replaced with numerical indexes 0 and 1 , which may have an impact on subsequent logic.

Workaround: Use preserve_keys parameter

PHP's array_slice() function actually supports an optional fourth parameter: preserve_keys . Its default value is false , which means the key name will be reset. If you set it to true , you can preserve the key names in the original array.

Corrected code example:

 $users = [
    'alice' => 'Alice Smith',
    'bob' => 'Bob Johnson',
    'carol' => 'Carol King',
    'dave' => 'Dave Lee'
];

$sliced = array_slice($users, 1, 2, true);
print_r($sliced);

Running results:

 Array
(
    [bob] => Bob Johnson
    [carol] => Carol King
)

The original key name was successfully preserved by setting preserve_keys to true .

Example of usage scenario: Pagination of data

Imagine that you are developing a user management system that uses array_slice() for pagination processing when displaying some user data:

 $allUsers = [
    'alice' => ['name' => 'Alice', 'email' => '[email protected]'],
    'bob' => ['name' => 'Bob', 'email' => '[email protected]'],
    'carol' => ['name' => 'Carol', 'email' => '[email protected]'],
    'dave' => ['name' => 'Dave', 'email' => '[email protected]']
];

$page = 1;
$pageSize = 2;
$offset = ($page - 1) * $pageSize;

$currentUsers = array_slice($allUsers, $offset, $pageSize, true);

foreach ($currentUsers as $username => $info) {
    echo "username: $username, Mail: {$info['email']}\n";
}

Output:

 username: alice, Mail: [email protected]
username: bob, Mail: [email protected]

Keeping the key names allows us to process directly through the username key, such as splicing URLs when used as user identifiers in templates or when editing functional links:

 echo "<a href=\"https://gitbox.net/user/edit.php?user=$username\">edit</a>";

summary

When using array_slice() , if you want to retain the key name of the original array, just set the fourth parameter to true :

 array_slice($array, $offset, $length, true);

This is a small detail, but it can significantly improve the robustness and maintainability of the code, especially when dealing with associative arrays and structured data. Keeping this in mind can avoid various logical errors and debugging troubles caused by key names loss.