How do you reset the index of an array after blowing out one of the elements?

For example:

$array[0] = "blank1";
$array[1] = "blank2";
$array[2] = "blank3";
$array[3] = "blank4";
$array[4] = "blank5";

unset($array[3]);

This will of course destroy blank4.

But now I'm left with a gap in the index like so:

$array[0]
$array[1]
$array[2]
$array[4]

Is there a way to reset the index so everything will be like this?:

$array[0]
$array[1]
$array[2]
$array[3]

    Originally posted by Installer
    array_merge()

    That merges 2 arrays together. I want to re-index the array.

      function reindex(&$the_array) {
      $temp = $the_array;
      $the_array = array();
      foreach($temp as $value) {
      $the_array[] = $value; 
      } 
      }
      

      This should do it. Just pass the array variable into reindex();

        $array = array('a', 'b', 'c', 'd');
        unset($array[2]);
        $array = array_merge($array);
        echo '<pre>';
        print_r($array);
        echo '</pre>';
        
        // Displays:
        // Array
        // (
        //     [0] => a
        //     [1] => b
        //     [2] => d
        // ) 

        Here's what the manual says, in case you're wondering:

        If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

          Thanks madwormer2

          that did the trick 🙂

            Edit: Just as a coding exercise, here's a function that more closely mimics "array_merge()" with one argument:

            function reindex_numeric($arr)
            {
                $i = 0;
                foreach ($arr as $key => $val) {
                    if (ctype_digit((string) $key)) {
                        $new_arr[$i++] = $val;
                    } else {
                        $new_arr[$key] = $val;
                    }
                }
                return $new_arr;
            }

            It reindexes numeric keys starting from 0 while leaving non-numeric keys as they are.

              Thank you for that Installer.

              I understand how that works now. I'll be using merge for future re-indexes 🙂 TY

                Write a Reply...