169

I have array that i had to unset some indexes so now it 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 missing all i need to do is reset indexes so they show [0]-[3].

MrWhddite333
  • 1,751
  • 2
  • 12
  • 8
  • 5
    This is most definitely not a duplicate of [**How do you reindex an array in PHP?**](http://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php) Sharing a solution does not establish duplicity. – David N. Jafferian Apr 13 '17 at 02:08

4 Answers4

358

Use array_values.

$myarray = array_values($myarray);
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
115
$myarray = array_values($myarray);

array_values

Alfwed
  • 3,307
  • 2
  • 18
  • 20
20

array_values does the job :

$myArray  = array_values($myArray);

Also some other php function do not preserve the keys, i.e. reset the index.

AKS
  • 4,618
  • 2
  • 29
  • 48
Drasill
  • 3,917
  • 29
  • 30
1

This might not be the simplest answer as compared to using array_values().

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

krishna
  • 4,069
  • 2
  • 29
  • 56