tags:

views:

1254

answers:

12

I am trying to learn more about the PHP function sprintf() but php.net did not help me much as I am still cofused, why would you want to use it?

Take a look at my example below...

Why use this...

$output = sprintf("Here is the result: %s for this date %s", $result, $date);

When this does the same and is easiar IMO to write...

$output = echo 'Here is the result: ' .$result. ' for this date ' .$date;

Am I missing something here?

+29  A: 

sprintf has all the formatting capabilities of the original printf which means you can do much more than just inserting variable values in strings.

For instance, specify number format (hex, decimal, octal), number of decimals, padding and more. Google for printf and you'll find plenty of examples. The wikipedia article on printf should get you started.

Isak Savo
Years ago I wrote a nice function for zero-padding numbers. Used for ages before realizing I could simply do `sprintf('%03d', $num)`
DisgruntledGoat
+1  A: 

Some of the typical cases are where you need more precise control over the output format. It can be tricky to for example make sure a specific value has specific amount of spaces padded to front, depending on its length, or that a number is outputted in a specific precise format.

There are plenty of examples in the PHP manual

Also what comes to your example of "easier to write".. While the echo may be easier to write, the sprintf is easier to read, especially if you have a lot of variables.

Another reason to use sprintf or printf might be that you want to let a user define the output format of some value - you can safely allow them to define a sprintf compatible output format.

Oh, and your example is actually wrong for one part. sprintf returns the string, but echo does not - echo immediately outputs it and returns nothing, while sprintf just returns it.

Jani Hartikainen
+1  A: 
  1. If you've used C/C++, then you would be used to the sprintf function.

  2. There is a good chance that the second line is less efficient. Echo is designed as an output command, whereas sprintf is designed to do string token substitution. I'm not a PHP person, but I suspect that there are more objects involved with the echo. If it acts like Java would, it creates a new string each time something is added to the list, so you'd end up with 4 strings created.

Paul
Recent editions of Java will convert String concatenation to a StringBuilder behind the scenes.
RodeoClown
+12  A: 

There are many use cases for sprintf but one way that I use them is by storing a string like this: 'Hello, My Name is %s' in a database or as a constant in a PHP class. That way when I want to use that string I can simply do this:

$name = 'Josh';
// $stringFromDB = 'Hello, My Name is %s';
$greeting = sprintf($stringFromDB, $name);
// $greetting = 'Hello, My Name is Josh'

Essentially it allows some separation in the code. If I use 'Hello, My Name is %s' in many places in my code I can change it to '%s is my name' in one place and it updates everywhere else automagically, without having to go to each instance and move around concatenations.

macinjosh
A: 

Sometimes I got something like this, which I consider a little more easier to read:

$fileName = sprintf('thumb_%s.%s', 
                    $fileId,
                    $fileInfo['extension']);
vise
+3  A: 

Another use of sprintf is in localized applications as the arguments to sprintf don't have to be in the order they appear in the format string.

Example:

$color = 'blue';
$item = 'pen';

sprintf('I have a %s %s', $color, $item);

But a language like French orders the words differently:

$color = 'bleu';
$item = 'plume';

sprintf('J\'ai un %2$s %1$s', $color, $item);

(Yes, my French sucks: I learned German in school!)

In reality, you'd use gettext to store the localized strings but you get the idea.


Ken Keenan
+2  A: 

The best reason that I have found is that it allows you to place all the language strings in your language file were people can translate and order them as needed - yet you still know that no matter what format the string is in - you wish to show the users name.

For example, your site will say "Welcome back [[User]]" on the top of the page. As the programmer you don't know or care how the UI guys are going to write that - you just know that a users name is going to be shown somewhere in a message.

So you do can embed the message into your code without worring about what that message actually is.

Lang file (EN_US):

...
$lang['welcome_message'] = 'Welcome back %s';
...

Then you can support any type of message in any language by using this in your actual php code.

sprintf($lang['welcome_message'], $user->name())
Xeoncross
I have never had to worry about doing language files but this does seem like one of the most useful uses to me
jasondavis
+4  A: 

It's easier to translate.

echo _('Here is the result: ') . $result . _(' for this date ') . $date;

Translation (gettext) strings are now:

  • Here is the result:
  • for this date

When translated to some other language it might be impossible or it results to very weird sentences.

Now if you have

echo sprintf(_("Here is the result: %s for this date %s"), $result, $date);

Translation (gettext) strings is now:

  • Here is the result: %s for this date %s

Which makes much more sense and it's far more flexible to translate to other languages

raspi
+1  A: 

I usually use sprintf to ensure that a id that come from the user input is an integer for example:

// is better use prepared statements, but this is practical sometimes
$query = sprintf("SELECT * from articles where id = %d;",$_GET['article_id']);

Also is used to do rudimentary templates (for html mails or other things), so you can reuse a the the template in many places:

$mail_body = "Hello %s, ...";
$oneMail = sprintf($mail_body, "Victor");
$anotherMail = sprintf($mail_body, "Juan");

It's very useful also to format numbers in different representations (octal, control the decimal place, etc).

Castro
Isn't it easier just to use intval($_GET["article_id"])? Well, actually it took more typing...*notes down your method"Dag nabbit.
A: 

As mentioned, it allows formatting of the input data. For example, forcing 2dp, 4-digit numbers, etc. It's quite useful for building MySQL query strings.

Another advantage is that it allows you to separate the layout of the string from the data being fed into it, almost like feeding in paramaters. For example, in the case of a MySQL query:

// For security, you MUST sanitise ALL user input first, eg:
$username = mysql_real_escape_string($_POST['username']); // etc.
// Now creating the query:
$query = sprintf("INSERT INTO `Users` SET `user`='%s',`password`='%s',`realname`='%s';", $username, $passwd_hash, $realname);

This method does of course have other uses, such as when printing output as HTML, etc.

Edit: For security reasons, when using a technique as above you must sanitise all input variables with mysql_real_escape_string() before using this method, to prevent MySQL insertion attacks. If you parse unsanitised input, your site and server will get hacked. (With exception to, of course, variables which have been completely constructed by your code and are guaranteed to be safe.)

That code is vulnerable to SQL injection. Use placeholders, not query interpolation!
@duskwuff - Used as is, you're right. Sorry, I've amended my answer.
A: 
define('TEXT_MESSAGE', 'The variable "%s" is in the middle!');

sprintf(TEXT_MESSAGE, "Var1");
sprintf(TEXT_MESSAGE, "Var2");
sprintf(TEXT_MESSAGE, "Var3");
Mee
A: 

nice answer guys

nice guy
Not such a nice answer, nice guy. Should be a nice comment instead.
deceze