Home >Backend Development >PHP Tutorial >How to Reindex PHP Arrays Starting from 1 Instead of 0?

How to Reindex PHP Arrays Starting from 1 Instead of 0?

DDD
DDDOriginal
2024-12-25 16:14:09629browse

How to Reindex PHP Arrays Starting from 1 Instead of 0?

Reindexing Arrays with Starting Index of 1 in PHP

When dealing with arrays, it can be necessary to reindex them for various reasons. This includes starting the index at a different value, such as 1 instead of the default 0. Here's how to accomplish this in PHP:

Starting at 0

To reindex an array starting at 0, use the array_values() function, which returns an array containing the values of the original array:

$iZero = array_values($arr);

Starting at 1

For a starting index of 1, utilize the array_combine() and range() functions:

$iOne = array_combine(range(1, count($arr)), array_values($arr));

This combines an array of consecutive integers starting at 1 with the values of the original array.

Function References

  • [array_values()](https://www.php.net/manual/en/function.array-values.php)
  • [array_combine()](https://www.php.net/manual/en/function.array-combine.php)
  • [range()](https://www.php.net/manual/en/function.range.php)

The above is the detailed content of How to Reindex PHP Arrays Starting from 1 Instead of 0?. 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