Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

Why the the newline doesn't work with printf() in PHP

IGNORE THIS QUESTION. ASKED IN ERROR:

What's the difference between the following 2 printf statements:

printf($variable, "
");

printf("Hello
");

The newline gets ignored in the 1st printf() statement. But it works fine with the 2nd statement.

The only way I can use the new line is by splitting the 1st statement in to 2 separate statements:

printf($variable);
printf("
");

This sounds like a query from an absolute novice however I feel the newline was supported pretty good in Java but not in PHP.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

is being ignored because as stated in documentation first parameter is format which should be printed and rest of parameters are values which this format can use, for instance:

$num = 2.12; 
printf("formatted value = %.1f", $num);
//      ^^^^^^^^^^^^^^^^^^^^^^   ^^^^
//             |                  |
//             format             |
// value which can be put in format in place of `%X` where `X` represents type

will print formatted value = 2.1 because in format %.1f you decided to print only one digit after dot in floating point number.

To make format use string argument you need to use %s placeholder like in case of print("hello %s world","beautiful") which would put beautiful in place of %s and print hello beautiful world.

Now lets back to your code. In printf($variable, " "); $variable represents format, and it most probably doesn't have any %s for string in it which would let you put use " " argument in this format. This means that " " will be ignored (not used in format) so will not be printed.

Code like this

printf("Hello
");

or

printf($variable);
printf("
");

doesn't have this problem because it explicitly use in format which should be printed.

So it seems that you may either want to use

printf("%s
", $value) 

which seems like overkill because you can simply concatenate strings using . operator and print them like

print($value."
")

or

echo $value."
";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...