Wednesday, January 27, 2016

PHP: Using str_pad() to format text

PHP: Book List


$header="BOOK LIST";

$arr=array(
  'AYN RAND'=> 'Calumet K', 
  'ERNEST HEMINGWAY' =>' Wuthering Heights',
  'JOAN DIDION'=> 'Victory', 
  'RAY BRADBURY' => 'Fahrenheit 451 ',
  'GEORGE R.R. MARTIN' => 'Game of Thrones',
  'MARK TWAIN' => 'The Adventures of Tom Sawyer',
  'Stephen King' => 'The Shining',
  'James Patterson' => 'Alex Cross',
  'C. S. Lewis' => 'The Chronicles of Narnia',
  'Edgar Rice Burroughs' => 'Tarzan',
);

echo "<p>";
  
print(str_pad($header,60,"/",STR_PAD_BOTH)); //60 chars across: pad on both sides
  
echo "</p>";

foreach($arr as $author => $book){
  echo "<p>";
  print(str_pad($author,30,'.')); //30 chars across: default pad right side
  print(str_pad($book,30,'.',STR_PAD_LEFT)); //30 chars across: pad on left side
  echo "</p>";
  

//Result

/////////////////////////BOOK LIST//////////////////////////
AYN RAND...........................................Calumet K
ERNEST HEMINGWAY.......................... Wuthering Heights
JOAN DIDION..........................................Victory
RAY BRADBURY.................................Fahrenheit 451
GEORGE R.R. MARTIN...........................Game of Thrones
MARK TWAIN......................The Adventures of Tom Sawyer
Stephen King.....................................The Shining
James Patterson...................................Alex Cross
C. S. Lewis.........................The Chronicles of Narnia
Edgar Rice Burroughs..................................Tarzan

No comments:

Post a Comment