Home > Backend Development > PHP Tutorial > How Can I Reorder Array Keys in PHP to Start from 0?

How Can I Reorder Array Keys in PHP to Start from 0?

DDD
Release: 2024-12-09 00:02:10
Original
273 people have browsed it

How Can I Reorder Array Keys in PHP to Start from 0?

Reordering Array Keys with array_values

Encountering arrays with non-sequential keys can be a common scenario in programming. Consider an array like the one below, where the keys are not in the optimal order of 0, 1, 2, 3, and so on:

array(
  0 => 'val',
  2 => 'val',
  3 => 'val',
  5 => 'val',
  7 => 'val'
);
Copy after login

In situations like this, it becomes necessary to reset the keys to the desired sequence. PHP provides a convenient function called array_values specifically designed for this purpose.

The array_values function creates a new array with sequential keys starting from 0. It takes the original array as its argument and returns a new array with the values from the original array, but with keys set to consecutive integers.

$reindexed_array = array_values($old_array);
Copy after login

By using array_values, you can easily reindex your array, resulting in the following desired output:

array(
  0 => 'val',
  1 => 'val',
  2 => 'val',
  3 => 'val',
  4 => 'val'
);
Copy after login

The above is the detailed content of How Can I Reorder Array Keys in PHP to Start from 0?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template