function string_format(string|Stringable $formatSpec, ...$values): stringThere are two main functions providing fundamental functionality.
The string_format() function is designed to return formatted string
and the print_format() function prints the value immediately returning void.
The string_format() function takes at least one argument which is the format
specification and variadic arguments which can be positional arguments along
with named arguments and returns formatted string.
function string_format(string|Stringable $formatSpec, ...$values): stringstring_format() function formats the string given by $formatSpec and value
arguments passed in form of variadic arguments either positional or named ones.
The format specification used to format a string.
Can be passed in form of a single value to format or more (using named arguments notation or positional ones) which are formatted and replaced in result string value.
Returns the formatted string value.
use fmt\string_format;
$message = string_format(
'{when:Y-m-d} is {temp:0.1f}°C and is {cond}',
temp: 32, // (1)
cond: 'sunny', // (2)
when: new DateTimeImmutable('now'), // (3)
);
var_dump($message);Foo
Bar
Baz fooo
string(34) "2020-08-20 is 32.0°C and is sunny."Caution | All positional arguments require passing before all named arguments as this is how named arguments works in PHP. |
Above usage of string_format() is way more clean and easier to read equivalent of:
$message = \sprintf(
'%3$s is %1$0.1f°C and is %2$s',
32,
'sunny',
(new DateTimeImmutable('now'))->format('Y-m-d')
);
var_dump($message);Note | If we care about full equivalent with the same argument order all arguments
need to be referenced by a positional index only with use of 3$ notation. |
The print_format() function takes at least one argument which is the format
specification and variadic arguments which can be positional arguments along
with named arguments and prints formatted string.
function print_format(string|Stringable $formatSpec, ...$values): voidprint_format() function formats the string given by $formatSpec and value
arguments passed in form of variadic arguments either positional or named ones
just like the string_format() does.
The format specification used to format a string.
Can be passed in form of a single value to format or more (using named arguments notation or positional ones) which are formatted and replaced in result string value.
No value, the function return is void.
use fmt\print_format;
print_format('Hello {}!', 'John');Hello John!