Home >Backend Development >PHP Tutorial >How to Reorganize Array Keys After Deleting Elements in PHP?

How to Reorganize Array Keys After Deleting Elements in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 15:29:02963browse

How to Reorganize Array Keys After Deleting Elements in PHP?

Reorganizing Array Keys After Element Deletion

When working with arrays, it's essential to maintain proper key organization after deleting elements. The provided code snippet:

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

Removes elements from the array with values 1 and 2, but it results in a sparse array, with missing keys:

<code class="php">array(3) {
  [2] => int(3)
  [3] => int(4)
  [4] => int(5)
}</code>

To restore zero-based keys, use the array_values() function:

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

This function returns a new array with sequential integer keys, starting from 0. The resulting array will be:

<code class="php">array(3) {
  [0] => int(3)
  [1] => int(4)
  [2] => int(5)
}</code>

Using array_values() ensures that the array keys are properly reset after element deletion, making it easier to access and manipulate the array.

The above is the detailed content of How to Reorganize Array Keys After Deleting 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