How to Reindex a PHP Array with Consecutive Numeric Keys?

Susan Sarandon
Release: 2024-10-25 06:45:02
Original
767 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!