How to Re-Index a PHP Array and Start Index Number Sequence From a Specific Value?

Re-index PHP array to start from a specific value

If you wish to re-index a PHP array, making the resulting array start from a specified index that sequentially adds indexes after, then you can use the following code snippet:

function reindexArray(array $arr, int $startIndex = 0): array
{
    $newArr = [];
    $i = 0;

    foreach ($arr as $value) {
        $newArr[$startIndex + $i] = $value;
        $i++;
    }

    return $newArr;
}
$arr = [ 2 => 'foo', 6 => 'bar', 4 => 'baz' ];
$newArr = reindexArray($arr, 5);

var_dump($newArr); // [5 => 'foo', 6 => 'bar', 7 => 'baz']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.