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

How to Reindex a PHP Array Starting from 1?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 19:17:11886browse

How to Reindex a PHP Array Starting from 1?

Reindex an Array and Shift Indexes to Start from 1 in PHP

You have an array with keys starting from 2, and you want to reindex it with keys starting from 1.

To achieve this, you can use a combination of array functions in PHP:

  1. Use array_values() to Extract Object Values:
$values = array_values($originalArray);
  1. Use array_combine() and range() to Reindex with Indexes Starting from 1:
$reindexedArray = array_combine(
    range(1, count($values)),
    $values
);

Output:

array (

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

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

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

)

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