Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Filling in the 'gaps' in an array

Tags:

arrays

merge

php

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!

like image 779
aboved Avatar asked Dec 29 '25 19:12

aboved


1 Answers

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.

like image 115
user187291 Avatar answered Jan 01 '26 08:01

user187291



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!