How to make alignment on console in php

user519846 picture user519846 · Aug 12, 2011 · Viewed 23.8k times · Source

I am trying to run a script through command prompt in PHP and trying to show the result in tabular form. But due to different character length of words I am not able to show the result properly align.

I want result like this

Book                  ISBN      Department
Operating System      101       CS
C                     102       CS
java                  103       CS

Can anyone please help me to get this output like this in php on console.

Thanks in advance

Answer

Hnatt picture Hnatt · Aug 12, 2011

If you don't want (or not allowed for some reason) to use libraries, you can use standard php printf / sprintf functions.

The problem with them that if you have values with variable and non-limited width, then you will have to decide if long values will be truncated or break table's layout.

First case:

// fixed width
$mask = "|%5.5s |%-30.30s | x |\n";
printf($mask, 'Num', 'Title');
printf($mask, '1', 'A value that fits the cell');
printf($mask, '2', 'A too long value the end of which will be cut off');

The output is

|  Num |Title                          | x |
|    1 |A value that fits the cell     | x |
|    2 |A too long value the end of wh | x |

Second case:

// only min-width of cells is set
$mask = "|%5s |%-30s | x |\n";
printf($mask, 'Num', 'Title');
printf($mask, '1', 'A value that fits the cell');
printf($mask, '2', 'A too long value that will brake the table');

And here we get

|  Num |Title                          | x |
|    1 |A value that fits the cell     | x |
|    2 |A too long value that will brake the table | x |

If neither of that satisfies your needs and you really need a table with flowing width columns, than you have to calculate maximum width of values in each column. But that is how PEAR::Console_Table exactly works.