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:
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!