Home >Backend Development >PHP Tutorial >How to Reindex an Array After Removing Elements in PHP?

How to Reindex an Array After Removing Elements in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 13:48:29782browse

How to Reindex an Array After Removing Elements in PHP?

Reindexing an Array after Removing Elements

When unsetting elements from an array, it can cause the array keys to become discontinuous. To reset the keys to be zero-based again, you can employ the following method:

Using array_values():

PHP provides the array_values() function, which returns a new array with numerically reindexed keys, starting from zero. To use it, simply pass the original array as an argument:

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

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

$array = array_values($array);

print_r($array);</code>

Output:

Array ( [0] => 3 [1] => 4 [2] => 5 )

By using array_values(), the keys in the modified array are now reindexed to be continuous and start from zero.

The above is the detailed content of How to Reindex an Array After Removing 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