This time to bring you how to do PHP reset array as a continuous digital index, so that PHP resets the array as a continuous digital index of the considerations, the following is the actual case, together to see.
For example, a PHP array like this:
$arr = Array ( 1 = ' Apple ', 3 = ' banana ', 5 = ' orange ');
You want to convert to an array like this:
$arr = Array ( 0 = ' Apple ', 1 = ' banana ', 2 = ' orange ');
1, the recommended way Array_values method
This works for both normal and associative arrays
<?php $arr = Array ( 1 = ' Apple ', 3 = ' banana ', 5 = ' orange '), Print_r (Array_values ($arr)); $arr 1 = array ( ' name ' = ' Jerry ', ' age ' = +, ' height ' = ' 18cm '); Print_r (Array_values ($arr 1) );
Output Result:
[Root@localhost php]# php array.php Array ( [0] = Apple [1] = Banana [2] = orange) Array (
[0] = Jerry [1] [ 2] = 18cm)
2. Using the Array_merge method
If the method only gives an array and the array is a numeric index, the key name is re-indexed in a sequential manner. So it can only be applied to numeric indexes.
<?php $arr = Array ( 1 = ' Apple ', 3 = ' banana ', 5 = ' orange '); Print_r (Array_merge ($arr)); $arr 1 = array ( ' name ' = ' Jerry ', ' age ' = +, ' height ' = ' 18cm '); Print_r (Array_merge ($arr 1));
Output Result:
[Root@localhost php]# php array.php Array ( [0] = Apple [1] = Banana [2] = orange) Array (
[name] = Jerry [age] = [height] = 18cm)
3. Loop traversal
The most primitive way, bloated and not elegant, strongly resisted.
<?php function Resetarr ($arr) { $temp = array (); foreach ($arr as $v) { $temp [] = $v; } return $temp; } $arr = Array ( 1 = ' Apple ', 3 = ' banana ', 5 = ' orange '); Print_r (Resetarr ($arr)); $arr 1 = array ( ' name ' = ' Jerry ', ' age ' = +, ' height ' = ' 18cm '); Print_r (Resetarr ($arr 1));
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP Operation string Segmentation array
What are the ways to implement a PHP merge array and retain key values?
php implementation prevents SQL injection method summary