(919) 964-9842
(919) 964-9842

Creating Rows And Columns Dynamically With PHP, HTML, And CSS

I am referring back to my own example all the time when it comes to creating a table dynamically in HTML. You have a situation where you have an array of items, and you need to place, let’s say, 4 in a row and push the next 4 into another row and so on. What happens when the total number of items in the array is not fixed? What about when your total number of items doesn’t divide evenly? This solution takes care of that.

First, you need to set up your array, running count of items in your array, and number of columns you want to use. For example, if you want 4 items per row, you would enter 4 here.

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
$programmed = array('PHP','SQL','HTML/CSS', 'JavaScript', 'Python', 'Ruby', 'SASS', 'jQuery', 'NodeJS', 'Express', 'Prototype', 'Backbone', 'AJAX', 'Gulp', 'Composer');

function sectionedRows($array, $columns = 4)
{
    $count = 0;
    $html = '<div class="container">';

    foreach ($array as $a) {
        if ($count % $columns == 0) {
            $html .= '<div class="row">';
        }
       
        $html .= '<div class="column">' . $a . '</div>';

        $count++;

        if ($count % $columns == 0 || $count == count($array)) {
            $html .= '</div>';
        }
    }

    $html .= '</div>';

    return $html;
}

echo sectionedRows($programmed, 4);
?>

Based on if the count is divisible by the number of columns you chose, it will create and close rows, giving you columns and rows. There's also an important OR logic piece that handles if you have gotten to the end of the array. This way, regardless if it's divisible or not, the row will be closed if you don't have any more elements to parse through.

Super simple and quick code! But definitely usable! Let me know if you have any questions down below.

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *