Coder Perfect

Is it possible to reindex an array in PHP? [duplicate]

Problem

I had to unset certain indexes in an array, so it now looks like

$myarray [0] a->1
         [1] a-7 b->3
         [3] a-8 b->6
         [4] a-3 b->2

As you can see, [2] is absent. All I have to do now is change the indexes such that [0]-[3] are displayed.

Asked by MrWhddite333

Solution #1

Use array_values.

$myarray = array_values($myarray);

Answered by Alex Turpin

Solution #2

$myarray = array_values($myarray);

array_values

Answered by Alfwed

Solution #3

array values is the right tool for the job:

$myArray  = array_values($myArray);

Other php functions, such as index reset, do not keep the keys.

Answered by Drasill

Solution #4

When compared to using array values, this may not be the simplest solution ().

Try this

$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
    foreach($arrays as $k => $item)
    {
    $array[$i]=$item;
        unset($arrays[$k]);
        $i++;

    }

print_r($array);

Demo

Answered by krishna

Post is based on https://stackoverflow.com/questions/7558022/php-reindex-array