Home >Backend Development >PHP Tutorial >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:
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:
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!