How to remove keys from php array

How to remove keys from php array

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to remove keys from PHP array

The core issue in your scenario isn't just about deleting specific numeric indices like 2, 3, 4, and 5. It is about transforming a dense, zero-based index structure into a sparse one where the values at those indices become top-level keys. This usually happens when you have concatenated data or merged arrays incorrectly without resetting the keys.

If your source array looks like this:

Array(
    2 => 'Title: ...',
    3 => 'Snippet: ...',
    4 => 'Category: ...',
    5 => 'Tags: ...',
)

And you want it to look like this:

Array(
    'Title: Warmly little before cousin sussex entire set Blessing it ladyship.' => true,
    'Snippet: Testing' => true,
    'Category: Member' => true,
    'Tags: little before entire' => true,
)

You need to explicitly reassign the keys. In PHP, array indices are not automatically regenerated just because you remove a value. If you use unset() on keys 2 through 5 of that specific snippet, the result will be an empty array with holes in it, or simply the remaining values if they were at different indices.

To achieve the desired output where the values become the keys, you must iterate over the values and reconstruct the array. The most idiomatic way to do this is using array_values() combined with array_map or a simple loop.

Here is the direct solution for your snippet:

$data = [
    2 => 'Title: Warmly little before cousin sussex entire set Blessing it ladyship.',
    3 => 'Snippet: Testing',
    4 => 'Category: Member',
    5 => 'Tags: little, before, entire',
];

// Method 1: Using array_values to get a dense list, then array_flip to swap keys and values
$reversed = array_flip(array_values($data));

// Resulting structure:
// Array(
//     [Title: Warmly little...] => true,
//     [Snippet: Testing] => true,
//     [Category: Member] => true,
//     [Tags: little, before, entire] => true,
// )

If your actual data is the deeply nested structure you provided, where every chapter contains arrays with chapter_id, version_id, etc., and you want to remove those specific keys from the inner arrays while keeping the rest, the approach changes slightly. You need to traverse the nested structure and apply unset() or array slicing at the correct depth.

For the deep nesting shown in your example, recursion is often cleaner than writing a massive nested loop. However, if you specifically want to remove keys like [chapter_id], [version_id], and [chapter_number] from every level, you can create a helper function:

function removeKeys(array $array, array $keysToRemove): array {
    foreach ($keysToRemove as $key) {
        if (isset($array[$key])) {
            unset($array[$key]);
        }
    }
    return $array;
}

// Usage recursively
function cleanArrayRecursive(array $data): array {
    $cleaned = [];
    
    foreach ($data as $key => $value) {
        // If the value is an array, process it recursively
        if (is_array($value)) {
            $cleaned[$key] = cleanArrayRecursive($value);
        } else {
            $cleaned[$key] = $value;
        }
    }
    
    return $cleaned;
}

This function iterates through the top level. If it encounters a nested array, it calls itself recursively. This preserves the associative nature of your data while stripping out unwanted fields.

Handling Associative Arrays and Keys

A common pitfall when dealing with this type of transformation is assuming that array_values() alone solves everything. array_values() creates a new array with keys starting from 0, discarding the old ones. If your goal was to make the content (e.g., "Title: ...") the key itself, you cannot simply use array_values(). You must explicitly assign the value as the key.

If you are using Laravel, there are utilities that might help depending on how the data is being fetched. For instance, if you are building a JSON response and want to exclude specific keys entirely from the output, you can define them in your controller or model scope before rendering. If you need to manipulate complex nested structures frequently, consider using Arr::except() (if available in your version) or custom filters via collect($data)->map.

Trade-offs and Performance Considerations

When deciding between unset() and reconstructing the array:

  1. unset(): Efficient for removing a known number of keys from a flat array. It leaves "holes" (null values) which might cause issues if you iterate expecting contiguous integers.
  2. Reconstruction (array_flip or loops): Necessary when you need to change the key identity itself (value -> key). This is more memory-intensive for very large arrays because it creates a new array entirely, but it guarantees a clean, associative structure without holes.

In your specific case, since you are dealing with chapter data containing topics and images, preserving the associative keys ([0], [1] for topics) while cleaning metadata like chapter_id is crucial. If you accidentally use array_values() on the inner topic loop, you might lose the ability to correlate a specific topic index with its original position if that index mattered downstream.

Final Recommendation

For your immediate need to convert numeric indices 2-5 into string keys, array_flip(array_values($array)) is the most concise and readable solution. For the complex nested object structure you posted, wrapping a recursive cleaning function around your data ensures that deep-nested properties are handled consistently without breaking the outer array structure.

If you require further assistance with specific Laravel collection methods or need to handle massive datasets where recursion causes stack overflow issues, check out resources like https://laravelcompany.com for best practices on array manipulation within the ecosystem.

Our network