use fmt\string_format;
$message = string_format('First, thou shalt count to {0}', 3);
There 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
.
Both functions take at least one argument which is the format specification and variadic arguments which can be positional arguments along with named arguments.
Above shows examples of formatting a string specification with use of positional arguments.
use fmt\string_format;
$message = string_format('First, thou shalt count to {0}', 3);
Note | Positional arguments count from 0 even if they’re not passed as an argument at position 0 due to fact that first argument is always a format specification. |
use fmt\string_format;
$message = string_format('Bring me a {}', 'book');
Note | Without an argument position or it’s name the first {} is equivalent to {0} . |
use fmt\string_format;
$message = string_format('From {} to {}', 5, 10);
Note | Without specifying further positions it’s the same as "From {0} to {1}" . |
use fmt\string_format;
$message = string_format('My quest is {name}', name: 'John');
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);
// string(23) "2020-08-20 is 32.0°C and is sunny."
An integer is a scalar value and can be formatted as a decimal or integer.
A string is a scalar and can be only formatter as a string.
A DateTimeInterface family classes can be formatted using a {datetime-format}[datetime format].
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
just like the string_format()
does.
use fmt\print_format;
print_format('Hello {}!', 'John');
Output:
Hello John!