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.

php Courses
php Courses
php Courses
Reindexing PHP Arrays: Using array_values, array_merge, and Manual Loops

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.

$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));

Output:

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

2. Using array_merge – reindexes only when the input array has numeric keys, so it is suitable for purely indexed arrays.

$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));

Output:

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

3. Manual iteration (loop) – the most explicit but verbose way, creating a new array by iterating over the original.

<?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));
?>

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendArrayarray_valuesarray mergeReindex
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.