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

11

u/Dicebar Jan 05 '22

I think most people disagree that sprintf() is more concise, and instead view it as unneeded complexity.

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

Kinda like disliking ternary operators within other constructs...personal preference!

0

u/grsftw Jan 05 '22

Yes but let’s say you have to grab a value from a model or array. It starts to get sloppy for anything but the simplest use came IMO.

8

u/Meek_braggart Jan 05 '22

$s = "My {$db->spouse} has {$db->petNumber} {$db->petType} and that makes me {$feelThings}";

Not so messy.

3

u/stfcfanhazz Jan 06 '22

Agreed. Like if you're calling a method or something. For situations like that or for large strings with lots of values to interpolate, I prefer sprintf. But for simple situations, concatenating a string with a value is OK too. No need to be a purist for either approach IMO