Home >Backend Development >PHP Tutorial >Three ways to reset arrays to consecutive numerical indexes in PHP
Three ways for PHP to reset an array to a continuous numeric index
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. Recommended method array_values method
This method is applicable to both ordinary arrays and associative arrays
'jerry', 'age' => 16, 'height' => '18cm' ); print_r(array_values($arr1));
Output result:
[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
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 can only be applied to numeric index .
##
'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. The most primitive way of looping through
is bloated and not elegant enough, so I strongly resist it.
'jerry', 'age' => 16, 'height' => '18cm' ); print_r(resetArr($arr1));That’s it!For more related knowledge, please visit
PHP Chinese website!
The above is the detailed content of Three ways to reset arrays to consecutive numerical indexes in PHP. For more information, please follow other related articles on the PHP Chinese website!