What's the difference between echo and printf?
问题:
回答1:
If you search the differences in any search engines, you'll get your answer. For example below is one use for printf:
You can use this function to format the decimal places in a number:
$num = 2.12;
printf("%.1f",$num);
prints:
2.1
And of course this is only just one use. Another good sample that i use is below:
If you are printing data in a "pre" tag, courier font, or otherwise non-variable length font (like a terminal), you might have use for printf's justify feature.
$value1 = "31298";
$value2 = "98";
print "<pre>\n";
printf ("%'.-15.15s%'.6.6s\n", $heading1, $value1);
printf ("%'.-15.15s%'.6.6s\n", $heading2, $value2);
print "</pre>\n";
?>
And lots of other usage.
回答2:
The main difference is that printf receives first a format string, with placeholders (those % signs you see), and can even accept some formatting parameters (like %2d, which would show 2 digits for a number).
Echo is, instead, just displaying the string. When you do "$i bar", the string is first expanded with the value of $i, and then sent to the echo function to be shown.