Home >Backend Development >PHP Tutorial >How to Reindex a PHP Array Starting from Index 1?

How to Reindex a PHP Array Starting from Index 1?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 09:10:11690browse

How to Reindex a PHP Array Starting from Index 1?

Reindexing Arrays in PHP with Indexes Starting from 1

To reindex an array in PHP with indexes starting from 1, you can use a combination of array manipulation functions. Here's how to achieve this:

PHP Code:

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

// Get the values of the array, reindexing from 0
$values = array_values($arr);

// Create a new array, combining new indexes starting from 1 with the values
$reindexed = array_combine(range(1, count($arr)), $values);

// Print the reindexed array
print_r($reindexed);

Explanation:

  • array_values() is used to extract the values from the original array, reindexing it from 0.
  • range() generates an array of consecutive integers starting from 1, which will be used as the new keys.
  • array_combine() combines the new keys with the values to create the reindexed array.

Result:

The reindexed array will have indexes starting from 1, as desired:

Array
(
    [1] => Array
        (
            [title] => Section
            [linked] => 1
        )

    [2] => Array
        (
            [title] => Sub-Section
            [linked] => 1
        )

    [3] => Array
        (
            [title] => Sub-Sub-Section
            [linked] =>
        )
)

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