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
Release: 2024-10-30 08:33:27
Original
910 people have browsed it

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];
Copy after login

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>
Copy after login

This will result in an array with missing keys:

[
    2 => 3,
    3 => 4,
    4 => 5
]
Copy after login

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>
Copy after login

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
]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template