1

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'
    }

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The output of $newArray that is.
1
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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.