[Previous] [Contents] [Next]

Padding strings

A simple method to space strings is to use the str_pad( ) function:

string str_pad(string input, int length [, string padding [, int pad_type]])

str_pad function

str_pad function pad a string to a certain length with another string. This function accepts four parameters:

  1. input string

  2. length no padding takes place if length is negative, less than or equal to the input

  3. padding the pad string (optional)

  4. pad_type STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH

Characters are added to the input string so that the resulting string is characters in length. The following example shows the simplest form of str_pad( ) that adds spaces to the end of the input string:

// prints "PHP" followed by three spaces
echo str_pad("PHP", 6);

An optional string argument padding can be supplied that is used instead of the space character. By default, padding is added to the end of the string. By setting the optional argument pad_type to STR_PAD_LEFT or to STR_PAD_BOTH, the padding is added to the beginning of the string or to both ends. The following example shows how str_pad( ) can create a justified index:

$players =
   array("DUNCAN, king of Scotland"=>"Larry",
         "MALCOLM, son of the king"=>"Curly",
         "MACBETH"=>"Moe",
         "MACDUFF"=>"Rafael");
echo "<pre>";
// Print a heading
echo str_pad("Dramatis Personae", 50, " ", STR_PAD_BOTH) . "\n";
// Print an index line for each entry
foreach($players as $role=>$actor)
  echo str_pad($role, 30, ".")
      . str_pad($actor, 20, ".", STR_PAD_LEFT) . "\n";
echo "</pre>";

The example prints:

                Dramatis Personae
DUNCAN, king of Scotland.....................Larry
MALCOLM, son of the king.....................Curly
MACBETH........................................Moe
MACDUFF.....................................Rafael

[Previous] [Contents] [Next]