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

12

u/sprain_mr Jan 05 '22

I love sprintf. But you have to know it first. The other syntax looks more like what a beginner would do as it‘s more obvious. I used to do that, too.

4

u/MDChristie Jan 05 '22

But why is it any better than the first syntax (or the similar but IMHO preferable "My {$spouse} has {$petNumber}....")?

The other syntax looks more like what a beginner would do as it‘s more obvious

Obvious is good. Quality code should be obvious and as easy to read as possible. If you're going to make something harder to read there should be a good reason for it.

Sure, if you're using sprintf for it's more power features, by all means. But if you're literally just joining a few strings it's cleaner to just concatenate/interpolate.