tags:

views:

89

answers:

4

Hey gurus,

I've got a php array (obtained through checkbox values in a form - as you know checkboxes only show up in the _POST variable when they are not set).

Array
(
    [2] => 0,2
    [3] => 0,3
)

I need a way to 'fill in' the gaps between the range 0-5. So above would look like (filling the empty spaces with '-1'. I tried array_merge() with an array filled with '-1' but that didn't work.

Array
(
    [0] => -1
    [1] => -1
    [2] => 0,2
    [3] => 0,3
    [4] => -1
    [5] => -1
)

I think I may have gone down the wrong road with the problem I am trying to solve, but I have put too much time into this solution to back out - a feeling I am sure most of you are familiar with(!)

Cheers!

+4  A: 

Why not just do it in a loop?

for ($i = 0; $i <= 5; $i++)
{
    if (!isset($array[$i]))
    {
        $array[$i] = -1;
    }
}
Chad Birch
+1  A: 

If you array is variable length you would want to use:

  for ($i = 0; $i <= sizeof($array); $i++)
    {
        if (!isset($array[$i]))
        {
            $array[$i] = -1;
        }
    }
dweebsonduty
This wouldn't feed the OPs needs. In his example the array has to values but he wants to fill it with **5** values. With your code, only the first two elements would be set.
Felix Kling
Actually I dont think this would work in your case. But it may be useful to someone else.
dweebsonduty
LOL Felix, I just thought about that and commented as you were...
dweebsonduty
+3  A: 

array_merge doesn't work, but '+' does!

$a = array(2 => 22, 3 => 33);
$b = $a + array_fill(0, 6, -1);

the key order is wrong though, so you might want to ksort it.

stereofrog
Thanks stereofrog, I went with this in the end (code below for anyone doing something similar with _POST. Just for future reference, does anyone know which is most processor friendly between this and the above foreach?
aboved
theoretically, the loop should be faster, but negligibly so
stereofrog
@aboved you shouldn't care of processor with such a case. 5 or even 100 iterations wouldn't make processor too much work. though you don't need this loop at all.
Col. Shrapnel
A: 

You don't need to fill any gaps

Col. Shrapnel