"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Reindex an Array in PHP with `array_values()`?

How to Reindex an Array in PHP with `array_values()`?

Published on 2024-11-11
Browse:855

How to Reindex an Array in PHP with `array_values()`?

Reindexing an Array in PHP

In PHP, you may encounter situations where you have an array with unset indices, resulting in gaps in the index sequence. To address this, you need to reindex the array to ensure a continuous index order.

How to Reindex an Array Using array_values

The array_values() function provides a straightforward solution for reindexing an array. It extracts the values from the original array and assigns them to new keys with sequential indices starting from 0.

To reindex your array, simply use the following code:

$myarray = array_values($myarray);

After executing this code, your $myarray will be reindexed as follows:

[0] => a->1
[1] => a-7 b->3
[2] => a-8 b->6
[3] => a-3 b->2

The gaps in the previous index sequence have now been removed, and the array's indices range from 0 to 3.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3