Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display php-cli output in columns

Tags:

php

I want to output data with variable length in columns in a php-cli script

Example:

$pepole = Array(
  'Mirco Dellarovere' => 'Artista',
  'Nino Pepe' => 'Attore',
  'Zoe Yan' => 'Futurista',
  'Mino' => 'Elettricista'
);

foreach($pepole as $name => $work)
  {
  echo "$name\t$work\n";
  }

The output will be

Mirco Dellarovere       Artista
Nino Pepe       Attore
Zoe Yan Futurista
Mino    Elettricista

but i want it this way

Mirco Dellarovere       Artista
Nino Pepe               Attore
Zoe Yan                 Futurista
Mino                    Elettricista

how to?

:) thanks

like image 563
nulll Avatar asked Jul 06 '11 15:07

nulll


2 Answers

You can pad $name to ensure a standard number of characters. Just ensure that the number of characters(20) is equal to or larger than the length of the longest name:

echo str_pad( $name, 20 ) . $work . "\n";
like image 148
George Cummins Avatar answered Oct 24 '22 00:10

George Cummins


Tabs/pads are boring.

Use sprintf with a predefined $mask. You can specify column widths and alignment.

In example below 20 is the width of the first column. If you want to adjust alignment you can add a - or + to the column like "%-20s %s\n". There are many formatting options. See http://php.net/manual/en/function.sprintf.php

$mask = "%20s %s\n";
foreach($pepole as $name => $work)
{
  echo sprintf($mask, $name, $work);
}
like image 2
Kyle Anderson Avatar answered Oct 23 '22 23:10

Kyle Anderson