Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use sprintf function in PHP?

Tags:

php

printf

I am trying to learn more about the PHP function sprintf() but php.net did not help me much as I am still confused, 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 easier to write IMO:

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

Am I missing something here?

like image 723
JasonDavis Avatar asked Sep 06 '09 20:09

JasonDavis


2 Answers

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.

like image 172
Isak Savo Avatar answered Sep 21 '22 18:09

Isak Savo


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.

like image 34
joshwbrick Avatar answered Sep 20 '22 18:09

joshwbrick