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

1

u/TransientVoltage409 Jan 06 '22

The first programming language I ever learned was BASIC, which used string concatenation ('+') exclusively. Simple, easy. Later I learned C (where there is no string type at all) and printf. Not really better or worse IMO. Different. Far more power and flexibility if you need it, but not like you have to wade through a swamp to do something simple. By force of inertia I tend to use printf in the general case in PHP and Java too - I've written a lot of C - but it's just one tool in the box.

[Also in C, one can prefer snprintf to avoid buffer overflow, or a lovely version call asprintf that allocates the needed buffer on demand. Not relevant in PHP, but neat.]