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

How to Reorder Array Keys After Unsetting Elements?

Susan Sarandon
Release: 2024-10-29 09:16:30
Original
874 people have browsed it

How to Reorder Array Keys After Unsetting Elements?

Reordering Array Keys After Unsetting Elements

When unsetting elements from an array, the array keys may become disjointed, affecting the index order. To resolve this, you can use the array_values() method.

Consider the following code:

<code class="php">$array = array(1, 2, 3, 4, 5);

foreach ($array as $i => $info) {
    if ($info == 1 || $info == 2) {
        unset($array[$i]);
    }
}

print_r($array); // Outputs: [3, 4, 5] (disjointed keys)</code>
Copy after login

To reassign keys, use array_values():

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

print_r($array); // Outputs: [0 => 3, 1 => 4, 2 => 5] (reordered keys)</code>
Copy after login

array_values() creates a new array with values preserved and keys starting from zero index, effectively reordering the array keys.

The above is the detailed content of How to Reorder Array Keys After Unsetting Elements?. 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