Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the printf() function in PHP?

Tags:

php

printf

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.

like image 467
David Gard Avatar asked May 15 '12 11:05

David Gard


1 Answers

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:

  • echo: http://php.net/manual/en/function.echo.php
  • printf: http://php.net/manual/en/function.printf.php

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

Examples

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);
like image 89
Adriano Repetti Avatar answered Oct 18 '22 22:10

Adriano Repetti