How to Rebase Array Keys After Unsetting Elements?

Patricia Arquette
Release: 2024-10-30 06:20:02
Original
319 people have browsed it

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

If we unset certain keys using a foreach loop:

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

This would result in a disjointed array:

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

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

$array = array_values($array);
Copy after login

This function returns a new array with sequentially rebased keys:

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!