The printf Function
The printf
function outputs a string,
formatted according to a specified format.
The first parameter accepts a format string, and the subsequent parameters are the values for substitution. The format string uses special characters (format specifiers), which start with the %
sign and control the output formatting.
Syntax
printf(string $format, mixed ...$values): int
Format Specifiers
Specifier | Description |
---|---|
%s |
String |
%d |
Signed integer (decimal) |
%u |
Unsigned integer (decimal) |
%f |
Floating-point number (locale dependent) |
%F |
Floating-point number (non-locale aware) |
%c |
Character by ASCII code |
%x |
Integer in hexadecimal (lowercase) |
%X |
Integer in hexadecimal (uppercase) |
%o |
Integer in octal system |
%b |
Integer in binary system |
%e |
Scientific notation (lowercase) |
%E |
Scientific notation (uppercase) |
%g |
Short form of %e or %f |
%G |
Short form of %E or %F |
%% |
Percent sign |
Example
In this example, %s
will be replaced with
the word 'apples'
, and %d
with the number
3
:
<?php
$product = 'apples';
$num = 3;
printf('product - %s, amount - %d', $product, $num);
?>
Code execution result:
'product - apples, amount - 3'
Example
In this example, the parameters are swapped and numbering is introduced:
<?php
$num = 3;
$product = 'apples';
printf('product - %2$s, amount - %1$d', $num, $product);
?>
Code execution result:
'product - apples, amount - 3'
Example
In this example, the number is needed several times, so numbering is introduced:
<?php
$num = 3;
$product = 'apples';
printf('product - %1$s, amount - %2$d, count - %2$d', $product, $num);
?>
Code execution result:
'product - apples, amount - 3, count - 3'
See Also
-
the
sprintf
function,
which performs a similar operation but returns the result -
the
number_format
function,
which formats a number