Home  >  Article  >  Backend Development  >  How to Reindex a PHP Array with Consecutive Numeric Keys?

How to Reindex a PHP Array with Consecutive Numeric Keys?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 06:45:02828browse

How to Reindex a PHP Array with Consecutive Numeric Keys?

Reindexing PHP Arrays

To resolve the issue of missing array indexes, you can use the array_values function in PHP. This function reindexes an array by creating a new one with consecutive numeric keys starting from 0.

Example:

<code class="php">$myarray = [
    0 => 'a->1',
    1 => 'a-7',
    '3' => 'a-8',
    4 => 'a-3',
];

$reindexedArray = array_values($myarray);

print_r($reindexedArray);
// Output:
// Array
// (
//     [0] => a-1
//     [1] => a-7
//     [2] => a-8
//     [3] => a-3
// )</code>

By calling array_values($myarray), we create a new array $reindexedArray that has consecutive indexes from 0 to the last element. This effectively reindexes the original array and removes any missing indexes.

The above is the detailed content of How to Reindex a PHP Array with Consecutive Numeric Keys?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn