1 | initial version |
To reindex an array in PHP in such a way that the indexes start from 1, you can simply use the array_values() function. This function returns a new array containing all the values of the original array, with numeric keys starting from 0 and increments by 1. By subtracting 1 from all the keys of the resulting array, we can reindex the array with keys starting from 1.
Here's an example code:
<?php
$myArray = array("apple", "banana", "cherry");
$reindexedArray = array_values($myArray);
$finalArray = array_combine(range(1, count($reindexedArray)), $reindexedArray);
print_r($finalArray);
?>
Output:
Array
(
[1] => apple
[2] => banana
[3] => cherry
)
In this example, we first get the reindexed array using the array_values()
function. Then, we use the array_combine()
function to combine the numeric array keys starting from 1 with the values of the reindexed array, creating a new array with keys starting from 1.