Home >Backend Development >PHP Tutorial >How to Reindex a PHP Array from Zero-Based to One-Based?

How to Reindex a PHP Array from Zero-Based to One-Based?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 21:27:52295browse

How to Reindex a PHP Array from Zero-Based to One-Based?

Reindexing Arrays from Zero to One in PHP

Given an array where the indices begin from zero, it may be necessary to reindex the array with indices starting from one. This can be achieved using array functions in PHP.

Reindexing from Zero to One

To reindex the array from zero to one, use the following steps:

  1. Get the values of the existing array using the array_values() function. This function creates a new array containing only the values of the original array, with the indices reset to zero.
  2. Combine the new values with the desired indices using the array_combine() function. The range() function can be used to create the desired indices, which start from one.

Example:

Consider the original array:

$arr = [
    2 => [
        'title' => 'Section',
        'linked' => 1,
    ],
    1 => [
        'title' => 'Sub-Section',
        'linked' => 1,
    ],
    0 => [
        'title' => 'Sub-Sub-Section',
        'linked' => null,
    ],
];

To reindex the array with indices starting from one, use the following code:

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

The resulting $iOne array will be as follows:

[
    1 => [
        'title' => 'Section',
        'linked' => 1,
    ],
    2 => [
        'title' => 'Sub-Section',
        'linked' => 1,
    ],
    3 => [
        'title' => 'Sub-Sub-Section',
        'linked' => null,
    ],
]

Relevant Function Documentation:

  • [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 a PHP Array from Zero-Based to One-Based?. 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