The printf() or sprintf() function writes a formatted string to a variable.
Here is the Syntax:
sprintf(format,arg1,arg2,arg++)
format:
- %% - Returns a percent sign
- %b - Binary number
- %c - The character according to the ASCII value
- %d - Signed decimal number (negative, zero or positive)
- %e - Scientific notation using a lowercase (e.g. 1.2e+2)
- %E - Scientific notation using a uppercase (e.g. 1.2E+2)
- %u - Unsigned decimal number (equal to or greater than zero)
- %f - Floating-point number (local settings aware)
- %F - Floating-point number (not local settings aware)
- %g - shorter of %e and %f
- %G - shorter of %E and %f
- %o - Octal number
- %s - String
- %x - Hexadecimal number (lowercase letters)
- %X - Hexadecimal number (uppercase letters)
arg1:
- The argument to be inserted at the first %-sign in the format
string..(Required.)
arg2:
- The argument to be inserted at the second %-sign in the format
string. (Optional)
arg++:
- The argument to be inserted at the third, fourth, etc. %-sign in
the format string (Optional)
Example 1:
$number = 9;
$str = "New York";
$txt = sprintf("There are approximately %u million people in %s.",$number,$str);
echo $txt;
This will output:
There are approximately 9 million people in New York.
The arg1, arg2, arg++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.
Note: If there are more % signs than arguments, you must use
placeholders. A placeholder is inserted after the % sign, and consists
of the argument- number and "\$". Let see another Example:
Example 2
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f
<br>With no decimals: %1\$u",$number);
echo $txt;
This will output:
With 2 decimals: 123.00
With no decimals: 123
Another important tip to remember is that:
With printf() and sprintf() functions, escape character is not
backslash '\' but rather '%'. Ie. to print '%' character you need to
escape it with itself:
printf('%%%s%%', 'Nigeria Naira');
This will output:
%Nigeria Naira%
Feel free to explore the official PHP Documentation