|
This script outputs log (15.32) = 2.72916. For those of you who come from the C language, note that printf() does not provide any kind of substitution of backslash-escaped special characters, such as \n. If you want to use these special characters, ensure that you specify the value of format_specification using the double-quote syntax.
The traditional C implementation of printf() requires that a parameter be specified for each replacement directive stored in format_specification. As the directives are found, the interpreter moves from one parameter to the next until all substitutions are made.
Unfortunately, this approach can cause some serious trouble. Consider the case, for example, of using printf() as the basis for a system that supports multiple languages. The English sentence
"The [box/case] contains [three/five] pens"
can be translated into another language using a different construction, for example:
"There are [three/five] pens in the [box/case]"
It's clear that using printf() to provide a localization system flexible enough to support the construction forms of different languages would be difficult without the possibility of specifying which parameter should be used to provide a value for each replacement directive.
Luckily, PHP makes it possible to do so by using a slightly different directive syntaxall you need to do is prepend the number of the parameter, followed by a dollar sign ($), to the directive. For example, the following script:
<?php
function replace_me ($s) { printf ($s, 10, 'box'); }
replace_me ("There are %d pens in the %s\n"); replace_me ("The %2\$s contains %1\$s pens\n");
?>
returns the correct value despite the fact that the order of the parameters is inverted in the second string (notice how I have escaped the dollar signs using a backslash to ensure that they are not trapped by PHP's string declaration mechanism):
There are 10 pens in the box.
The box contains 10 pens.
The sprintf function takes the same parameters as printf(), but returns the string that results from its execution:
$a = printf ("%d cases of wine\n", 10);
Tags:
Add more tags...,
|