update page now

Voting

: three plus zero?
(Example: nine)

The Note You're Voting On

phpm at nreynolds dot me dot uk
21 years ago
array_chunk() is helpful when constructing tables with a known number of columns but an unknown number of values, such as a calendar month. Example:

<?php

$values = range(1, 31);
$rows = array_chunk($values, 7);

print "<table>\n";
foreach ($rows as $row) {
    print "<tr>\n";
    foreach ($row as $value) {
        print "<td>" . $value . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

?>

Outputs:

1 2 3 4 5 6 7 
8 9 10 11 12 13 14 
15 16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31 

The other direction is possible too, with the aid of a function included at the bottom of this note. Changing this line:
  $rows = array_chunk($values, 7);

To this:
  $rows = array_chunk_vertical($values, 7);

Produces a vertical calendar with seven columns:

1 6  11 16 21 26 31 
2 7  12 17 22 27 
3 8  13 18 23 28 
4 9  14 19 24 29 
5 10 15 20 25 30 

You can also specify that $size refers to the number of rows, not columns:
  $rows = array_chunk_vertical($values, 7, false, false);

Producing this:

1 8  15 22 29 
2 9  16 23 30 
3 10 17 24 31 
4 11 18 25 
5 12 19 26 
6 13 20 27 
7 14 21 28 

The function:

<?php

function array_chunk_vertical($input, $size, $preserve_keys = false, $size_is_horizontal = true)
{
    $chunks = array();
    
    if ($size_is_horizontal) {
        $chunk_count = ceil(count($input) / $size);
    } else {
        $chunk_count = $size;
    }
    
    for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) {
        $chunks[] = array();
    }

    $chunk_index = 0;
    foreach ($input as $key => $value)
    {
        if ($preserve_keys) {
            $chunks[$chunk_index][$key] = $value;
        } else {
            $chunks[$chunk_index][] = $value;
        }
        
        if (++$chunk_index == $chunk_count) {
            $chunk_index = 0;
        }
    }
    
    return $chunks;
}

?>

<< Back to user notes page

To Top