PHP command line plaintext table

Outputting tables on the command line is fiddlier than it sounds, requiring some string padding trickery. Here’s a quick-and-dirty function to insta-win!

An interesting quirk of this function is that it’s more difficult to determine the width of each column than to actually output the table, and that’s where the difficulty is really: determining, for each column, the width of the longest piece of content and padding it to account for cell spacing.

It’s not particularly clever though; it has no concept of headers (perhaps just provide the first row in uppercase) and doesn’t handle text wrapping, but for a quick-and-dirty table it does the job!

The Table function

function table($data) {

    // Find longest string in each column
    $columns = [];
    foreach ($data as $row_key => $row) {
        foreach ($row as $cell_key => $cell) {
            $length = strlen($cell);
            if (empty($columns[$cell_key]) || $columns[$cell_key] < $length) {
                $columns[$cell_key] = $length;
            }
        }
    }

    // Output table, padding columns
    $table = '';
    foreach ($data as $row_key => $row) {
        foreach ($row as $cell_key => $cell)
            $table .= str_pad($cell, $columns[$cell_key]) . '   ';
        $table .= PHP_EOL;
    }
    return $table;

}

Usage

To use this function, pass it a multi-array where each sub-array is a row and each sub-array item is a table cell:

echo table([
['FOO', 'BAR', 'FIZZ', 'BUZZ'],
['Lorem', 'Ipsum', 'Dolor', 'Emit'],
['Antiquated', 'Porcupine', 'Sandwich', 'Man'],
]);

When run in a command prompt, it’ll look something like this:

cli-table

Why?

I came upon this requirement while building a micro-framework for PHP console apps. I wanted it to have no dependencies so you could just drop a folder into a project and go, but could still use Composer if preferable (a la Slim). The logic was that if you were familiar with Composer you’re probably building something medium-to-large and would need something more kitchen-sink-like such as Synfony Console anyway.

To be honest this is probably one of those “reinventing the wheel” things, but I think it’s good to revisit old problems every once in a while with a perspective that’s fresh and more experienced. The blog CMS I’d make today would be very different from the one I’d have made 2 years ago, so here’s to reinventing the wheel — and telling yourself that your own re-invention is worthy of remark :)

Leave a Reply

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