Current Location: Home> Latest Articles> How to easily implement custom string alignment and padding by perfectly controlling the output format using the sprintf function and str_pad() function?

How to easily implement custom string alignment and padding by perfectly controlling the output format using the sprintf function and str_pad() function?

gitbox 2025-05-02

In daily PHP programming, we often need to output neatly aligned data, such as table-form lists, logging formats, command-line outputs, etc. If you are still using echo to manually splice spaces or tabs to achieve alignment, then it is time to let sprintf() and str_pad() help you easily handle these things.

1. sprintf(): a tool for formatting output

sprintf() is a function in PHP used to format strings. It allows us to format variables to be output according to the format template, which is very suitable for controlling the alignment of numbers and strings.

Example 1: Format numerical output

 $price = 19.9;
$formatted = sprintf("price:%.2f Yuan", $price);
echo $formatted; // Output:price:19.90 Yuan

sprintf() is very suitable for use in output alignment scenarios. For example, when outputting a set of data, we can set a fixed width for each column:

 $data = [
    ['name', 'quantity', 'price'],
    ['apple', 10, 2.5],
    ['banana', 5, 1.3],
    ['orange', 20, 3.75],
];

foreach ($data as $row) {
    printf("%-10s %-6d %6.2f Yuan\n", $row[0], $row[1], $row[2]);
}

The output results are uniform, and can be displayed in aligned manner no matter how big the number or how many decimal places are.

2. str_pad(): Easily implement character filling

Although sprintf() is powerful, in some cases we only need to simply align and fill the string left and right, and str_pad() comes in handy.

str_pad() function signature:

 str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
  • $string : original string

  • $length : Total length after filling

  • $pad_string : Characters used for padding

  • $pad_type : Fill the direction, optional STR_PAD_RIGHT , STR_PAD_LEFT or STR_PAD_BOTH

Example 2: Create a menu list of characters alignments

 $menu = [
    ['Log in', 'https://gitbox.net/login'],
    ['register', 'https://gitbox.net/signup'],
    ['Help Center', 'https://gitbox.net/help'],
];

foreach ($menu as $item) {
    $name = str_pad($item[0], 20, ' ', STR_PAD_RIGHT);
    echo $name . ' => ' . $item[1] . PHP_EOL;
}

Output:

 Log in                 => https://gitbox.net/login
register                 => https://gitbox.net/signup
Help Center             => https://gitbox.net/help

The alignment effect is clear at a glance!

3. Combination of sprintf() and str_pad()

Of course, the two functions can also be used in combination, suitable for more complex typesetting needs. For example, we can use sprintf() to process the format accuracy, and then fill in the column width through str_pad() :

 $items = [
    ['ID' => 1, 'name' => 'apple', 'price' => 2.5],
    ['ID' => 2, 'name' => 'banana', 'price' => 1.3],
    ['ID' => 3, 'name' => 'orange', 'price' => 3.75],
];

foreach ($items as $item) {
    $id = str_pad($item['ID'], 4, ' ', STR_PAD_RIGHT);
    $name = str_pad($item['name'], 10, ' ', STR_PAD_RIGHT);
    $price = str_pad(sprintf("%.2f", $item['price']), 6, ' ', STR_PAD_LEFT);
    echo "{$id}{$name}{$price} Yuan\n";
}

Output:

 1   apple       2.50 Yuan
2   banana       1.30 Yuan
3   orange       3.75 Yuan

Summarize

In terms of format control, sprintf() and str_pad() each have their own strengths:

  • sprintf() is suitable for formatting numbers, dates, strings, etc., and has powerful format template support;

  • str_pad() is suitable for filling the width and centering the string left and right;

  • The combination of the two can make the output layout more flexible and powerful.

By mastering these two functions, you can easily create a beautiful and neat text output interface, whether it is command line tools, log printing, or debugging output of background management pages. Make your PHP program look more professional, starting with output!