ADM
ADM

Reputation: 1610

PHP: filling arrays in multidimensional one to have the same number of elements

I have the following array with the days of one month grouped by days of the week.

Array
(
    [3] => Array
        (
            [0] => 1
            [1] => 8
            [2] => 15
            [3] => 22
            [4] => 29
        )

    [4] => Array
        (
            [0] => 2
            [1] => 9
            [2] => 16
            [3] => 23
            [4] => 30
        )

    [5] => Array
        (
            [0] => 3
            [1] => 10
            [2] => 17
            [3] => 24
            [4] => 31
        )

    [1] => Array
        (
            [0] => 6
            [1] => 13
            [2] => 20
            [3] => 27
        )

    [2] => Array
        (
            [0] => 7
            [1] => 14
            [2] => 21
            [3] => 28
        )

)

As you can see all the arrays have five elements but for the last two that have four.

How can I fill the last two arrays so they can also have five elements?

I'd like to fill them with empty values so when I'm printing an html table it'll print nothing after day 31

Thanks a lot

Upvotes: 0

Views: 2235

Answers (3)

billyonecan
billyonecan

Reputation: 20250

You can use array_pad() to do this.

example

$data = array(
    array(1, 2, 3, 4, 5),
    array(3, 4, 5),
    array(4, 9, 10, 11),
    array(1, 3, 5, 7, 8)
);

var_dump(array_map(function($val) { 
  return array_pad($val, 5, ''); 
}, $data));

outputs

array
  0 => 
    array
      0 => int 1
      1 => int 2
      2 => int 3
      3 => int 4
      4 => int 5
  1 => 
    array
      0 => int 3
      1 => int 4
      2 => int 5
      3 => string '' (length=0)
      4 => string '' (length=0)
  2 => 
    array
      0 => int 4
      1 => int 9
      2 => int 10
      3 => int 11
      4 => string '' (length=0)
  3 => 
    array
      0 => int 1
      1 => int 3
      2 => int 5
      3 => int 7
      4 => int 8

Upvotes: 0

faq
faq

Reputation: 3076

adding values to multid. array using array_push is like so:

array_push ($array[1]['something'], "value"); 

in your example:

array_push ($array[count($array)][4], 99); 
array_push ($array[count($array)-1][4], 99); 

Upvotes: 0

Havelock
Havelock

Reputation: 6968

If you really insist on having the fix for the data isntead of having it for the printing as the comment suggested, then you could use array_pad in something like this:

$days = array(....) // that's your original array
foreach($days as $key => $val){
    if(count($val)<5)
        $days[$key] = array_pad($val, 5, 0);
}

Where array_pad($val, 5, 0); fills the array with 0's till it reaches length 5.

Upvotes: 1

Related Questions