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.
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.
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.
We want the table to look like this:
Name | |
---|---|
Alice | [email protected] |
Bob | [email protected] |
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]);
}
?>
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 .
After executing the above code, the output result is as follows:
| Name | Mail |
--------------------------------------
| Alice | [email protected] |
| Bob | [email protected] |
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]");
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.