Zacky112
Zacky112

Reputation: 8879

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

Upvotes: 1

Views: 340

Answers (5)

user1545488
user1545488

Reputation: 13

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).

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212522

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

Upvotes: 0

timdev
timdev

Reputation: 62924

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.

Upvotes: 1

Thariama
Thariama

Reputation: 50840

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

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799560

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

Upvotes: 4

Related Questions