Home > Backend Development > PHP Tutorial > Three ways to reset arrays to consecutive numerical indexes in PHP

Three ways to reset arrays to consecutive numerical indexes in PHP

藏色散人
Release: 2023-04-09 06:48:02
forward
3525 people have browsed it

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

Want to convert to an array like this:

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

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

Output result:

[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

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

Related labels:
php
source:csdn.net
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