April 6, 2016 Javier Eguiluz

The Console component makes displaying tables in your commands a breeze:

1 2 3 4 5 6 7 8 9 10 11 use Symfony\Component\Console\Helper\Table ; $table = new Table ( $output ); $table -> setHeaders ( array ( 'ISBN' , 'Title' , 'Author' , 'Price' )) -> setRows ( array ( array ( '99921-58-10-7' , 'Divine Comedy' , 'Dante Alighieri' , '9.95' ), array ( '9971-5-0210-0' , 'A Tale of Two Cities' , 'Charles Dickens' , '139.25' ), )) ; $table -> render ();

By default, the widths of the columns are calculated automatically based on their contents. This is the commonly expected behavior, but some applications may need a more explicit control over the table design.

In Symfony 3.1, the Table helper lets you define the width of any or all the table columns. First, the new setColumnWidth($columnIndex, $columnWidth) method defines the width of the given column (column indexes start at 0 ):

1 2 3 4 5 6 7 8 // ... $table -> setHeaders ( ... ) -> setRows ( array ( ... )) -> setColumnWidth ( 0 , 15 ) -> setColumnWidth ( 3 , 10 ) ; $table -> render ();

This example sets the width of the first column (index 0 ) to 15 chars and the width of the fourth column (index 3 ) to 10 chars. The output of the command would be the following:

1 2 3 4 5 6 +-----------------+----------------------+-----------------+------------+ | ISBN | Title | Author | Price | +-----------------+----------------------+-----------------+------------+ | 99921-58-10-7 | Divine Comedy | Dante Alighieri | 9.95 | | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | 139.25 | +-----------------+----------------------+-----------------+------------+

Note Depending on the styles used by your table, the actual column width can be longer. For example, the default table style adds one white space on the left and right sides of each column, so their width will be increased by 2.

The given column widths are always considered the minimum column widths. If the contents don't fit, the column widths are increased up to the longest content length.

You can also set all column widths at once with the setColumnWidths(array $widths) method. Use 0 as the width of the columns you don't want to set explicitly:

1 2 3 4 5 6 7 // ... $table -> setHeaders ( ... ) -> setRows ( array ( ... )) -> setColumnWidths ( array ( 15 , 0 , 0 , 10 )) ; $table -> render ();