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']
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.