The vsprintf Function
The vsprintf
function is similar to sprintf
, but accepts arguments as an array,
not a variable number of parameters. The first parameter is a format string with
format specifiers, the second is an array of values for substitution. The format string uses special characters (format specifiers) that start with the %
sign and control the output formatting.
Syntax
vsprintf(string $format, array $args);
Format Specifiers
Specifier | Description |
---|---|
%s |
String |
%d |
Signed integer (decimal) |
%u |
Unsigned integer (decimal) |
%f |
Floating-point number (locale dependent) |
%F |
Floating-point number (not locale dependent) |
%c |
Character by ASCII code |
%x |
Integer in hexadecimal system (lowercase) |
%X |
Integer in hexadecimal system (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
Basic example of formatting a string with value substitution:
<?php
$res = vsprintf('Hello %s! Today is %s.', ['John', 'Monday']);
echo $res;
?>
Code execution result:
'Hello John! Today is Monday.'
Example
Using different format specifiers:
<?php
$res = vsprintf('%04d-%02d-%02d', [2023, 5, 12]);
echo $res;
?>
Code execution result:
'2023-05-12'
Example
Working with floating-point numbers:
<?php
$res = vsprintf('Price: $%.2f', [19.99]);
echo $res;
?>
Code execution result:
'Price: $19.99'