Home  >  Article  >  Backend Development  >  How to Rebase Array Keys After Unsetting Elements?

How to Rebase Array Keys After Unsetting Elements?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 06:20:02319browse

How to Rebase Array Keys After Unsetting Elements?

Rebase Array Keys After Unsetting Elements

When elements are removed from an array, its keys can become disjointed. This can be undesired, especially when maintaining proper indexing is important.

To rebase array keys after unsetting elements, you can use the array_values() function.

Consider the following array:

$array = array(1, 2, 3, 4, 5);

If we unset certain keys using a foreach loop:

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

This would result in a disjointed array:

array(3) {
  [2] => int(3)
  [3] => int(4)
  [4] => int(5)
}

To rebase the array keys, simply use array_values():

$array = array_values($array);

This function returns a new array with sequentially rebased keys:

array(3) {
  [0] => int(3)
  [1] => int(4)
  [2] => int(5)
}

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