How to add a missing index to an array in php?

Example:

I have an array like this:

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

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

+3
source share
4 answers

This should be faster for large arrays. For smaller arrays, any method will be executed.

$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);
+3
source

you can try a for () from the lowest index to the highest and full if it is empty

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

}

Alternatively, you can first count the number of elements in the array and wrap it in a function

 function completeIndexes($array)
    {

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

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

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

. , .

Edit

, Perr0_hunter , : P

+1

, , ,

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

Just create a new array and copy the values ​​into it. It will highlight new indexes sequentially

i.e.

$new_array = array();
for( $value in $old_array )
  $new_array[] = $value;
-1
source

Source: https://habr.com/ru/post/1706094/


All Articles