PHP.nl

sprintf

sprintf

Return a formatted string

string **sprintf** string $format mixed $values

Returns a string produced according to the formatting string . format

values

Returns a string produced according to the formatting string . format

Voorbeeld: Argument swapping

The format string supports argument numbering/swapping.

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
?>
There are 5 monkeys in the tree

However imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:

Voorbeeld: Wrong Argument Order

The format string supports argument numbering/swapping.

<?php
$num = 5;
$location = 'tree';

$format = 'The %s contains %d monkeys';
echo sprintf($format, $num, $location);
?>

We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

Voorbeeld: Use Order Placeholder

<?php
$num = 5;
$location = 'tree';

$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);
?>

An added benefit is that placeholders can be repeated without adding more arguments in the code.

Voorbeeld: Repeated Placeholder

<?php
$num = 5;
$location = 'tree';

$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
echo sprintf($format, $num, $location);
?>

When using argument swapping, the must come immediately after the percent sign (), before any other specifiers, as shown below. n$position specifier%

Voorbeeld: Specifying padding character

<?php
echo sprintf("%'.9d\n", 123);
echo sprintf("%'.09d\n", 123);
?>
......123
000000123

Voorbeeld: Position specifier with other specifiers

<?php
$num = 5;
$location = 'tree';

$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);
?>
The tree contains 0005 monkeys

Voorbeeld: : zero-padded integers

<?php
$year = 2005;
$month = 5;
$day = 6;

$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
echo $isodate, PHP_EOL;
?>

Voorbeeld: : formatting currency

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
echo $money, PHP_EOL;

$formatted = sprintf("%01.2f", $money);
echo $formatted, PHP_EOL;
?>
123.1
123.10

Voorbeeld: : scientific notation

<?php
$number = 362525200;

echo sprintf("%.3e", $number), PHP_EOL;
?>
3.625e+8

printf``fprintf``vprintf``vsprintf``vfprintf``sscanf``fscanf``number_format``date