This may seem like a really daft question, but what is the reason for the existence of the printf()
function in PHP?
It seems to me that that using echo
will achieve the exact same results, with the added bonus that you don't get confused if you have several variables being output on one line (true, you can use %1$s
as opposed to just %s
, but it can still get messey with a few variables all being declared).
I know you can also define the type of the variable, without the need to amend it before outputting the string, but to me that doesn't seem like enough to warrent creating a function.
Maybe I'm wrong, maybe I'm missing something obvious, but if someone can help me to understand why it exists (so that I know whether or not I should really be using it!) I'd appriciate it. Thanks.
echo
is language construct, printf
is a function. It means that so you won't be able to use echo
in the same way as printf
.
IT'S NOT JUST PERSONAL TASTE
Take a look to the manual pages for both functions:
This topic is discussed there, for example, you cannot call echo
with variable functions. Moreover the way they get and manage the input is different. If you do not need the parameters FORMATTING provided by printf
you should use echo
(it's slightly faster).
I insist again on some keywords: formatting and function.
The use of printf
isn't to concatenate strings or to build a string from placeholders but to do it with custom formatting (possibly from configuration, user inputs or whatever else).
I write some code to explain what I mean (original source in the links I posted).
This code is not valid, echo
is not a function so it won't return the printed value (you may use print
or sprintf
for this but print
does not provide string concatenation).
($some_var) ? echo 'true' : echo 'false';
Following code prints a formatted string, in this case the format comes from a literal variable but it may comes from (for example) a GET request or whatever else. Can you rewrite it with echo
and the formatting string taken from the configuration?
%format = "%'.-15.15s%'.6.6s\n";
printf($format, $heading1, $value1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With