Reindexing PHP Arrays: Using array_values, array_merge, and Manual Loops
This guide explains how to transform a PHP array with non‑sequential keys into a zero‑based sequential array by using the built‑in array_values function, the array_merge function, and a manual foreach loop, providing code examples and output for each method.
This article demonstrates how to convert a PHP associative array with non‑sequential numeric keys into a zero‑based sequential array.
1. Recommended method: array_values – works for both indexed and associative arrays.
<code>$arr = array(
1 => 'apple',
3 => 'banana',
5 => 'orange'
);
print_r(array_values($arr));
$arr1 = array(
'name' => 'jerry',
'age' => 16,
'height' => '18cm'
);
print_r(array_values($arr1));</code>Output:
<code>[root@localhost php]# php array.php
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Array
(
[0] => jerry
[1] => 16
[2] => 18cm
)</code>2. Using array_merge – reindexes only when the input array has numeric keys, so it is suitable for purely indexed arrays.
<code>$arr = array(
1 => 'apple',
3 => 'banana',
5 => 'orange'
);
print_r(array_merge($arr));
$arr1 = array(
'name' => 'jerry',
'age' => 16,
'height' => '18cm'
);
print_r(array_merge($arr1));</code>Output:
<code>[root@localhost php]# php array.php
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Array
(
[name] => jerry
[age] => 16
[height] => 18cm
)</code>3. Manual iteration (loop) – the most explicit but verbose way, creating a new array by iterating over the original.
<code><?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));
$arr1 = array(
'name' => 'jerry',
'age' => 16,
'height' => '18cm'
);
print_r(resetArr($arr1));
?>
</code>Each method successfully resets the keys to a continuous numeric sequence (0, 1, 2, …). The article also includes promotional details for a PHP online training class.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.