Forum Moderators: coopster

Message Too Old, No Replies

Newbie question - why use sprintf?

         

formasfunction

2:37 pm on May 13, 2008 (gmt 0)

10+ Year Member



Recently I've been reading up on sprintf and I think I understand how it functions but I'm at a loss as to where exactly to use it instead of simple string concatenation. I've seen people rave about it, I've seen it show up in other peoples' code, and I want to hop on the party train. Are there any tutorials out there that very clearly show its benefits over other methods? I found this one but the examples don't strike me as cleaner or more effective than concatenation.

[edited by: eelixduppy at 3:23 pm (utc) on May 13, 2008]
[edit reason] removed url [/edit]

eelixduppy

3:45 pm on May 13, 2008 (gmt 0)



I'd read further into the documentation for more specifics, however, the printf and sprintf functions are used to format strings and once you learn how the syntax works, it actually can become very useful. Consider the following example:

printf('binary: %b <br />char: %c <br /> int: %d <br /> float: %f <br />', 100, 100, 100, 100);

This will print the following:

binary: 1100100
char: d
int: 100
float: 100.000000

See how neat that was? ;) hehe...ok not really, but it was a simple example. To do the above with concatenation you'd have to cast the value into each type and then echo it to the browser. Kind of annoying, but not really. It would get more annoying, however, if you wanted to format the string even further. Then you'd be left even using other functions sometimes to format the string how you could easily with a simple printf format string. Look at some of the examples at the sprintf page and you'll see how easy it can make some tasks. For another example (taken from the documentation) I like this one:


$s = 'monkey';
printf("[%s]\n", $s); // standard string output
printf("[%10s]\n", $s); // right-justification with spaces
printf("[%-10s]\n", $s); // left-justification with spaces
printf("[%010s]\n", $s); // zero-padding works on strings too
printf("[%'#10s]\n", $s); // use the custom padding character '#'
printf("[%10.3s]\n", $s); // left-justification but with a cutoff of 3 characters

Look at the output.