tags:

views:

140

answers:

4

Example:

I have and array like this:

Array( [0] => Apple [2] => Orange [5] => Pear [8] => Pear )

there are a function to complete the missing indexes: 1,3,4,6,7????

A: 

If what you're trying to do is reorder the array so you get

Array( [0] => Apple [1] => Orange [2] => Pear [3] => Pear )

Just create a new Array and copy the values into it. It will allocate new indexes sequentially

i.e.

$new_array = array();
for( $value in $old_array )
  $new_array[] = $value;
Zoomzoom83
use array_Values() instead of your for loop
OIS
+1  A: 

you could try a for() from the lowest index to the highest and complete if it's empty

for($i = 0 ;$i <= 8 ; $i++) 
{
//if it's not set
if(!isset($array[$i]))
{
//set to empty
$array[$i] = "";
}

}

Additionally you could count first the number of elements on the array and wrap it in a function

 function completeIndexes($array)
    {

    $total = count($array);
     for($i = 0 ;$i < $total ; $i++) 

        {
        //if it's not set
        if(!isset($array[$i]))
        {
        //set to empty
        $array[$i] = "";
        }

        }
return $array; 
    }
PERR0_HUNTER
+1  A: 
for($i=0;i<count($array);++$i){
    $array[$i] = isset($array[$i])? $array[$i] : '';
}

It just fills the missing keys with an empty string, though. Not sure if this suits you.

Edit

Just noticed Perr0_hunter wrote pretty much the same thing before I did :P

Rob
+1  A: 

This should be faster for larger arrays. For smaller arrays any method will do.

$existingKeys = array_keys($array);

//you can use any value instead of null
$newKeys = array_fill_keys(range(min($existingKeys), max($existingKeys)), null);
$array += $newKeys;

//optional, probably not needed
ksort($array);
OIS