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 *

About Christina M. Gleason

Christina GleasonDeveloper who has been playing with websites since I was a preteen, it started with some tables and CSS creating a website about fairies (true story). Since then, I got a BS in Computer Science, and went to work on PHP-based websites and applications. I spent some time in custom frameworks, then a lot of time in custom WordPress development and Magento e-commerce. Industries I've worked in include logistics, healthcare, retirement communities, legal, spiritual, and HVAC.

I am an active knitter, and I also really enjoy scrapbooking and painting. Creativity has always been at my core, and I bring that into my daily workflow all the time. Lifting and working out is also important to me. I'm also married, have two daughters, and two rescue dogs Barlow and Sunshine.

Find me on: Ravelry | Instagram | Twitter | LinkedIn | GitHub