Current Location: Home> Latest Articles> How to implement a table output tool with sprintf

How to implement a table output tool with sprintf

gitbox 2025-04-28

In PHP, the sprintf function is used to format string output, which can help us build formatted tables. This article will show you how to implement a simple table output tool using the sprintf function.

1. Introduction to sprintf function

The sprintf function outputs a formatted string into a variable. Its basic usage is as follows:

 sprintf(format, args...)
  • format is a format string that defines the structure of the output content.

  • args... is the parameter corresponding to the placeholder in the format string.

Common formatting symbols include %s (string), %d (integral), %f (floating number), etc.

2. Use sprintf to output the table

Suppose we need to output a simple form that displays the user's name and email address. We can format each row of data through sprintf , and then splice these rows into a complete table.

2.1 Table structure

We want the table to look like this:

2.2 Generate tables using sprintf

First, we define the column title and data of the table and then format the output using sprintf .

 <?php

// Header
$header = sprintf("| %-10s | %-20s |\n", "Name", "Mail");

// Tabular data
$data = [
    ["Alice", "[email protected]"],
    ["Bob", "[email protected]"]
];

// Output table header
echo $header;
echo str_repeat("-", strlen($header) - 1) . "\n";  // Output divider

// 输出Tabular data
foreach ($data as $row) {
    echo sprintf("| %-10s | %-20s |\n", $row[0], $row[1]);
}

?>

2.3 Explain the code

  • sprintf("| %-10s | %-20s |\n", "name", "email"); generates the table header. %-10s means left alignment, with a width of 10 characters; %-20s means left alignment, with a width of 20 characters.

  • str_repeat("-", strlen($header) - 1) is used to generate dividers, with the same length as the width of the table header.

  • Then iterate through the data array through foreach loop, formatting the output of each row using sprintf .

2.4 Output result

After executing the above code, the output result is as follows:

 | Name       | Mail                  |
--------------------------------------
| Alice      | [email protected]       |
| Bob        | [email protected]         |

3. Customize the table format

You can adjust the format as needed, such as modifying the column width, alignment, or adding more columns. Just change the relevant part based on the format string of sprintf .

For example, if you want to be right-aligned, you can use %10s (specify the width and right-aligned):

 echo sprintf("| %10s | %20s |\n", "Alice", "[email protected]");

4. Summary

With the sprintf function, we can easily format and output tabular data. Although sprintf itself does not directly support the function of tables, through the formatting control it provides, we can easily implement a simple table output tool.