PHP printf function

 The PHP printf function can be used to output the formatted string. The operation process first inserts new characters into the original string and formats it, and then directly outputs the formatted new string on the web page. The usage is the same as sprintf The function is similar, but the difference is that the printf function can be formatted and output at one time. After the sprintf function is formatted, echo or print must be used to output the result. If the program does not need to be formatted after the string, For other processing, but to output to the web page immediately, the printf function is quite convenient.


Basic syntax of PHP printf function

string printf (string $format, $args1, $args2, $args3, $arg4, $arg5 ...)


The first parameter in the parentheses of the printf function, $format, is the original formatting conversion string, which may contain many formatting parts with percentages. You can set the format of the characters that will be brought in. About $ For format parameters, please refer to the parameter table on the sprintf function . Then there are many $args, which are the characters to be brought into the $format string. There can be many characters. Printf will bring in the $format string in order, complete the formatting, and finally format the new string. Output on the web page.

PHP printf function example 1
<?php
$string ='to';
$number = '5';
$format ='Welcome %s Wibibi.%f is float of %u.';
printf($format,$string,$number,$number) ;
?>
The output of the above example
Welcome to Wibibi.5.000000 is float of 5.
The example $format is a string containing 3% formatting symbols. Through the printf function, the $string and $number variables are brought into the percentage position of $format in sequence, and formatted. The first percentage is written as %s , Which means you want to format $string as a string, the second percentage is written as %f, which means you want to format $number as a floating point number, and the third percentage is written as %u, which means you want to format $number as a decimal Integer.

PHP printf function example 2: Control the number of decimal places of floating-point numbers
<?php
$number = '5';
$format = "%1\$.3f is float of %u.";
printf($format,$number,$number);
?>
The output of the above example
5.000 is float of 5.
In fact, to control the number of decimal places of floating-point numbers, only a little trick is needed. The first is that the content of the $format variable should be wrapped in double quotes ("") instead of single quotes (''). The second It is in the string, written as "%1\$.3f" as in the example, which means that three digits are reserved after the decimal point, and then the printf function can bring in $number and format it.

Post a Comment

0 Comments