tags:

views:

46

answers:

4

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 help me in understanding the call to the printf function.

+4  A: 

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

Ignacio Vazquez-Abrams
+3  A: 

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
Thariama
+1  A: 

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.

timdev
"We're going to [the movies] on [Friday]" vs "Wir gehen [am Freitag] miteinander [ins Kino]."
sarnold
A: 

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

Mark Baker