开发者

printf function in PHP

开发者 https://www.devze.com 2023-01-07 14:28 出处:网络
I\'m from a C background and understand basics of printf function. I came across the follwing code <?php

I'm from a C background and understand basics of printf function.

I came across the follwing code

<?php
printf('%4$d %2$s code for %3$3.2f %1$s', "hours", "coders", 9, 99);
?>

which prints:

99 coders code for 9.00 hours

Can anyone h开发者_如何转开发elp me in understanding the call to the printf function.


<n>$ means "use the nth argument, instead of whatever position you are in formatting specs".


The first argument of the printf function is a String that gets altered using the other arguments:

  • %4d - takes the 4th item after the comma and treats it as a decimal number
  • %2$s - takes the 2nd item after the comma and treats it as a String
  • %3$3.2f - takes the 3rd itam after the comma and treats it as a floating number with two decimal places
  • %1$s - takes the first item after the comma and treats it as a String


Ignacio's answer is correct.

One very useful application of this feature if you're using gettext for I18N. The order of substitution might change between one language and another. (though if you're wrapping stuff in calls to gettext, you'd be using sprintf).

I'm drawing a blank on a real-world example, guess I don't speak enough natural languages.


I think some of the confusion might have been an error in the code: %3$3.2f should read %3$.2f instead (but it works either way).


Not sure what the difficulty is, because it's fairly well documented in the manual:

The first argument is the format mask, subsequent arguments are values to insert into the format mask. Rules for masking are the same as in C. And like in C, output is sent directly to stdout

0

精彩评论

暂无评论...
验证码 换一张
取 消