Home > Backend Development > PHP Tutorial > How Do I Reindex a PHP Array to Start from 0?

How Do I Reindex a PHP Array to Start from 0?

Susan Sarandon
Release: 2024-12-07 17:25:12
Original
712 people have browsed it

How Do I Reindex a PHP Array to Start from 0?

Reindexing an Array

In PHP, arrays are dynamically indexed. This means that the keys of an array can be any arbitrary value, and they do not have to follow any specific pattern. However, there are times when you may want to reindex an array, such as when you need to reset the keys to a continuous sequence of numbers starting from 0.

Problem:

Consider the following array:

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

How can you reindex this array so that the keys go like 0, 1, 2, 3, 4?

Solution:

To reindex an array, you can use the array_values() function. This function takes an array as an input and returns a new array with the same values as the input array, but with the keys reindexed to start from 0.

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

In this example, $reindexed_array will be as follows:

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

The above is the detailed content of How Do I Reindex a PHP Array 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template