This article mainly shares with you a summary of several ways to reset an array to a continuous numeric index in PHP. It has a good reference value and I hope it can help everyone.
For example, a php array like this:
$arr = array( 1 => 'apple', 3 => 'banana', 5 => 'orange' );
Want to convert to an array like this:
$arr = array( 0 => 'apple', 1 => 'banana', 2 => 'orange' );
1. The recommended method is the array_values method
This method is suitable for ordinary arrays and Applicable to associative arrays
'jerry', 'age' => 16, 'height' => '18cm' ); print_r(array_values($arr1));
Output results:
[root@localhost php]# php array.php Array ( [0] => apple [1] => banana [2] => orange ) Array ( [0] => jerry [1] => 16 [2] => 18cm )
2. Use the array_merge method
This method if only one array is given and the array is numerically indexed, the key names will be re-indexed in a continuous manner. So it only works with numeric indexes.
'jerry', 'age' => 16, 'height' => '18cm' ); print_r(array_merge($arr1));
Output result:
[root@localhost php]# php array.php Array ( [0] => apple [1] => banana [2] => orange ) Array ( [name] => jerry [age] => 16 [height] => 18cm )
3. Loop traversal
The most primitive method is bloated and inelegant, so I strongly resist it.
'jerry', 'age' => 16, 'height' => '18cm' ); print_r(resetArr($arr1));
Related recommendations:
php numeric index array instance usage summary
How to retain numeric index in php array
How to convert the key index of the array into a numeric index
The above is the detailed content of Several PHP reset arrays to consecutive numeric indexes. For more information, please follow other related articles on the PHP Chinese website!