r/PHPhelp • • Jan 05 '22

Question: Why do PHP developers hate sprintf()?

I just can't figure it out. My background is in other languages. I get that sprintf() has had some fun issues in C when people don't properly account for length. But in PHP I see code all the time that, instead of using a very clear and concise sprintf(), use concatenations that are impossible to understand easily. Where does this come from? I'm used to something along the lines of:

$s = sprintf("My %s has %d %s and that makes me %s",
    $spouse, $petNumber, $petType, ($goodEmotion ? "happy" : "sad"));

In PHP, I am constantly seeing this:

$s = "My ".$spouse." has $petNumber $petType and that makes me "
    .$goodEmotion ? "happy" : "sad";

I'm honestly curious where this comes from. Is there a history of issues with sprintf() in PHP or is there something else?

edit: updated in markdown to show code

12 Upvotes

30 comments sorted by

View all comments

22

u/HolyGonzo Jan 05 '22 edited Jan 05 '22

PHP's variable interpolation simply makes it easier to read, in my opinion. It's more like natural language.

Imagine if you were talking to someone and you said, "My name is... I'll tell you in a second... and my job is.... I'll tell you that in a second, too. Gonzo and programmer."

Compare that to "My name is Gonzo and my job is programmer."

The use of sprintf() for basic string assembly is great when you don't have an alternative.

However, the string concatenation and interpolation makes it easy to read and ALSO easy to update. If I need to change the string to take out or add a variable, I don't need to insert a placeholder AND then figure out where to insert the value later.

I generally use sprintf() for shell scripts where I want some more advanced control over formatting/layout of content.

As far as -technical efficiency- goes, sprintf is more efficient than string concatenation or interpolation but since most PHP scripts are so short / tiny, small inefficiencies can be considered acceptable.