Search code examples
phphtmlstringformattingpre

Using <pre> tag to display data in columns?


I am working with PHP, and I want to display some data I have in an array (from a mysql db). The problem is that the first column not always have the same length, so while some rows containing shorter strings in the first column are all well aligned, in those with larger strings the second column gets aligned more to the right. The array looks like this:

$array[0][0] = "string0gvmdksd";
$array[0][1] = "42134";
$array[1][0] = "string1fges";
$array[1][1] = "234";
$array[2][0] = "string2gvmdksd sgdfsgdfg gffgdfg";
$array[2][1] = "87342";
$array[3][0] = "string3gffd";
$array[3][1] = "34";

I though about a solution. Getting the length of the longer string in the array[$i][0], then setting a variable with X number of spaces and a tab at the end (X is the longer string length), but that doesn't seem to work.

Here's my code:

function addTabs($input) {
    $length = 0;
    foreach($input as $entry) {
        if(strlen($entry[0])>$length) $length = strlen($entry[0]);
    }

    return str_repeat(" ", $length)."\t";
}

$data = "";
$tabs = addTabs( $array );
foreach( $array as $entry ) {
    $data .=  $entry[0] . $tabs . $entry[1] . "\n";
}

echo "<pre>$data</pre>";

But it displays:

string0gvmdksd                                  42134
string1fges                                 234
string2gvmdksd sgdfsgdfg gffgdfg                                    87342
string3gffd                                 34

Anyone has a solution for this?


Solution

  • If you really have to use <pre> tag then its best to use sprintf function like this:

    function maxLen($input) {
        $length = 0;
        foreach($input as $entry)
            if(strlen($entry[0])>$length) $length = strlen($entry[0]);
        return $length;
    }
    $len = maxLen($array);
    foreach( $array as $entry ) {
        $data .=  sprintf("%-$len"."s\t%s\n", $entry[0], $entry[1]);
    }
    echo "<pre>$data</pre>";
    

    OUTPUT

    string0gvmdksd                      42134
    string1fges                         234
    string2gvmdksd sgdfsgdfg gffgdfg    87342
    string3gffd                         34