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
Release: 2024-10-29 13:48:29
Original
792 people have browsed it

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

Output:

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

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!

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