vnsprintf()
Since version 1.0.0
Description
vnsprintf() - PHP's vsprintf() with added support for named arguments.
string vnsprintf(string $format, array $args);
Parameters
vnsprintf() takes two parameters:
$format(string) - a sprintf()-compatible format string, which may also contained named parameters$args(array) - a list of data values forsprintf()to use when$formatis expanded
PHP's built-in sprintf() already supports positional parameters:
echo vsprintf("The %1\$s sat on the %2\$s", ['cat', 'mat']) . PHP_EOL;
// output: The cat sat on the mat
vnsprintf() adds support for using named parameters too:
$args = [
'animal' => 'cat',
'place' => 'mat'
];
echo vnsprintf("The %animal\$s sat on the %place\$s", $args) . PHP_EOL;
// output: The cat sat on the mat
Return Values
vnsprintf() returns a string: the result of expanding $format using the data in $args.
Throws
vnsprintf() throws the following exception(s):
InvalidArgumentException- if you use a named parameter that can't be found in$args
Constraints
Internally, vnsprintf() converts $format into a sprintf()-compatible format string. As a result, $format must be one of the following:
- 100%-compatible with
sprintf(), or - use only named parameters, or
- use a mix of named parameters and positional parameters
You cannot do the following:
- use a mix of named parameters and normal (non-position) parameters in
$format - use a mix of positional parameters and normal (non-positional) parameters in
$format
If you do so, you'll get an error message from PHP.