Home >Backend Development >PHP Tutorial >How to Rebase Array Keys After Unsetting Elements in PHP?

How to Rebase Array Keys After Unsetting Elements in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 08:33:27916browse

How to Rebase Array Keys After Unsetting Elements in PHP?

Rebase Array Keys After Unsetting Elements

When working with arrays in PHP, it's common to encounter situations where you need to remove specific elements. However, unsetting elements can cause index gaps, potentially leading to confusion and incorrect results.

Problem

Consider an array with the following values:

$array = [1, 2, 3, 4, 5];

If you loop through the array and unset certain keys, the index gaps will become apparent:

<code class="php">foreach ($array as $i => $info) {
    if ($info == 1 || $info == 2) {
        unset($array[$i]);
    }
}</code>

This will result in an array with missing keys:

[
    2 => 3,
    3 => 4,
    4 => 5
]

Solution

To properly reset the array's keys, making them zero-based again, use the array_values() function:

<code class="php">$array = array_values($array);</code>

This function creates a new array with rebased keys, starting from zero.

Example

Applying array_values() to the above array would produce:

[
    0 => 3,
    1 => 4,
    2 => 5
]

The above is the detailed content of How to Rebase Array Keys After Unsetting Elements in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn