What's the difference between echo and printf?
-
1-1: You really should read the documentation. There is a significant difference between the two: http://php.net/manual/en/function.echo.php and http://www.php.net/manual/en/function.printf.php. – Tieson T. Mar 02 '13 at 22:31
-
everything is in the doc, in addition of what Tieson T. linked, see http://www.php.net/manual/en/function.sprintf.php for examples of formats – tmuguet Mar 02 '13 at 22:33
-
2Voted to reopen as this is the top result in google. – Tommy Arnold Jan 12 '18 at 19:08
2 Answers
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.

- 2,856
- 1
- 19
- 24
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.

- 1,849
- 10
- 21