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
Release: 2024-12-20 19:17:11
Original
959 people have browsed it

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);
Copy after login
  1. Use array_combine() and range() to Reindex with Indexes Starting from 1:
$reindexedArray = array_combine(
    range(1, count($values)),
    $values
);
Copy after login

Output:

array (

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

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

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

)
Copy after login

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!

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