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
Release: 2024-12-28 09:10:11
Original
689 people have browsed it

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);
Copy after login

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] =>
        )
)
Copy after login

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!

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