Keyur Padalia
Keyur Padalia

Reputation: 1138

Creating (Inserting) an array index

I have out put like below

[0]
{
    [0]=>'a'
    [2]=>'b'
    [5]=>'c'
    [6]=>'d'
}

No What i want is to insert un-created array index and set their values to '0'.

e.g: in this case i want output like below instead of the one above. can any one show me a sample of code please............. i tried to use array_fill() but didn't work it just inserts array index at end.

array_fill($b1, 1, "0");

Desired Output:

[0]
    {
        [0]=>'a'
        [1]=>'0'
        [2]=>'b'
        [3]=>'0'
        [4]=>'0'
        [5]=>'c'
        [6]=>'d'
    }

Upvotes: 1

Views: 84

Answers (4)

hakre
hakre

Reputation: 197712

Actually the first thing that comes to mind is sorting the array by keys (ksortDocs) after you have inserted the new elements:

ksort($array);

That probably already solves your issue. Everything else needs a bit more work.

Edit: In case you need to set all unset, that pretty straight forward as well:

$array = array(/* of set elements */);
$array += array_fill($start, $end, "0"); # fill only unset, array union operator
ksort($array);

Upvotes: 0

Sampson
Sampson

Reputation: 268344

Cycle through your array, watching the keys. Anytime the last iteration is more than 1 from the current key, perform a short while loop to catch up the array contents.

$newArray = array();
$lastKey = 0;

foreach ( $array as $key => $value ) {
  while ( $lastKey++ < $key ) $newArray[] = 0;
  $newArray[$key] = $value;
}

The output is:

Array
(
    [0] => a
    [1] => 0
    [2] => b
    [3] => 0
    [4] => 0
    [5] => c
    [6] => d
)

Demo: http://codepad.org/9EnowzqL

Upvotes: 1

Aziz
Aziz

Reputation: 20705

function fill_missing_keys($array)
{
    $arr_keys = array_keys ($array);
    $all_keys = range(0, max($arr_keys));  
    $missing_keys = array_diff($all_keys, $arr_keys);
    $zero_array = array_fill_keys ($missing_keys, '0');
    $filled_array = $array + $zero_array; 
    ksort($filled_array);
    return $filled_array;
}

Running example can be found here: http://ideone.com/jDU99

Upvotes: 1

symcbean
symcbean

Reputation: 48357

I believe (not tested) this will work:

  // get the first used key
  list($firstkey, $firstval)=each(asort($input_array));
  $input_array[$firstkey]=$firstval;

  // get the last used key
  list($lastkey, $lastval)=each(arsort($input_array));
  $input_array[$lastkey]=$lastval;

  $output_array=array_replace(array_fill($firstkey, $lastkey, 0), $input_array);

Upvotes: 0

Related Questions