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