sprintf

Return a formatted string

&reftitle.description; `string` `sprintf` `string` `format` `mixed` `values`

Returns a string produced according to the formatting string `format`.

&reftitle.parameters;

&strings.parameter.format;

`values`

&reftitle.returnvalues;

Returns a string produced according to the formatting string `format`.

&reftitle.errors; &strings.errors.sprintf;
&reftitle.changelog; &strings.changelog.sprintf;
&reftitle.examples;

### 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);
    ?>

&example.outputs;

    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:

    <?php
    $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:

    <?php
    $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.

    <?php
    $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 `n$` position specifier must come immediately after the percent sign (`%`), before any other specifiers, as shown below.

### Specifying padding character

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

&example.outputs;

    ......123
    000000123

### Position specifier with other specifiers

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

&example.outputs;

    The tree contains 0005 monkeys

### `sprintf`: zero-padded integers

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

### `sprintf`: formatting currency

    <?php
    $money1 = 68.75;
    $money2 = 54.35;
    $money = $money1 + $money2;
    echo $money;
    echo "\n";
    $formatted = sprintf("%01.2f", $money);
    echo $formatted;
    ?>

&example.outputs;

    123.1
    123.10

### `sprintf`: scientific notation

    <?php
    $number = 362525200;

    echo sprintf("%.3e", $number);
    ?>

&example.outputs;

    3.625e+8

&reftitle.seealso;

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