mirror of
https://github.com/sigmasternchen/php-doc-en
synced 2025-03-16 08:58:56 +00:00
Document argument swapping in [s]printf format string
git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@45073 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
parent
11c0f75b36
commit
5b77264051
1 changed files with 42 additions and 0 deletions
|
@ -1915,6 +1915,48 @@ soundex ("Lukasiewicz") == soundex ("Lissajous") == 'L222';
|
|||
</listitem>
|
||||
</orderedlist>
|
||||
</para>
|
||||
<para>
|
||||
As of PHP version 4.0.6 the format string supports argument
|
||||
numbering/swapping. Here is an example:
|
||||
<example>
|
||||
<title>Argument swapping</title>
|
||||
<programlisting role="php">
|
||||
$format = "There are %d monkeys in the %s";
|
||||
printf($format,$num,$location);
|
||||
</programlisting>
|
||||
</example>
|
||||
This might output, "There are 5 monkeys in the tree". But imagine we are
|
||||
creating a format string in a separate file, commonly because we would like to
|
||||
internationalize it and we rewrite it as:
|
||||
<example>
|
||||
<title>Argument swapping</title>
|
||||
<programlisting role="php">
|
||||
$format = "The %s contains %d monkeys";
|
||||
printf($format,$num,$location);
|
||||
</programlisting>
|
||||
</example>
|
||||
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:
|
||||
<example>
|
||||
<title>Argument swapping</title>
|
||||
<programlisting role="php">
|
||||
$format = "The %2\$s contains %1\$d monkeys";
|
||||
printf($format,$num,$location);
|
||||
</programlisting>
|
||||
</example>
|
||||
An added benefit here is that you can repeat the placeholders without
|
||||
adding more arguments in the code. For example:
|
||||
<example>
|
||||
<title>Argument swapping</title>
|
||||
<programlisting role="php">
|
||||
$format = "The %2\$s contains %1\$d monkeys. That's a nice %2\$s full of %1\$d monkeys.";
|
||||
printf($format,$num,$location);
|
||||
</programlisting>
|
||||
</example>
|
||||
</para>
|
||||
<simpara>
|
||||
See also: <function>printf</function>, <function>sscanf</function>,
|
||||
<function>fscanf</function>, and <function>number_format</function>.
|
||||
|
|
Loading…
Reference in a new issue