Home > Backend Development > PHP Tutorial > Several PHP reset arrays to consecutive numeric indexes

Several PHP reset arrays to consecutive numeric indexes

小云云
Release: 2023-03-21 09:10:01
Original
3317 people have browsed it

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' 
);
Copy after login

Want to convert to an array like this:


$arr = array( 
  0 => 'apple', 
  1 => 'banana', 
  2 => 'orange' 
);
Copy after login

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

Output results:


[root@localhost php]# php array.php  
Array 
( 
  [0] => apple 
  [1] => banana 
  [2] => orange 
) 
Array 
( 
  [0] => jerry 
  [1] => 16 
  [2] => 18cm 
)
Copy after login

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

Output result:


[root@localhost php]# php array.php  
Array 
( 
  [0] => apple 
  [1] => banana 
  [2] => orange 
) 
Array 
( 
  [name] => jerry 
  [age] => 16 
  [height] => 18cm 
)
Copy after login

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

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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template