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

2

u/Meek_braggart Jan 05 '22 edited Jan 05 '22

Honestly, your PHP code snippet is really poorly coded. Maybe people coded that way in PHP3 or 4 but no one codes that way anymore. Now I also hate the ternary operator at the end, just another place I have to pause to work out what will go where, but its at least current.

Not having a background in C I find the sprintf far harder to read and since I have to work out variable types (which I really don't need to worry about for an echo statement like this) its harder to code too.

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

1

u/grsftw Jan 05 '22

I see code like I presented all the time. Just look through GitHub or the history of forums like this one.

1

u/Meek_braggart Jan 05 '22

Doesn’t make it good code. No one would mix concatenation with inline strings and then hang a ternary off the end. Well maybe a student or something.

1

u/grsftw Jan 06 '22

That’s my point. It’s very common in the wild. I’m trying to figure out why that style is common with PHP devs.

2

u/Meek_braggart Jan 06 '22

Over the decades, sure it’s common. If you limit your GitHub searches to a few years I would bet it’s less so.

I mean if you want to know why that type of coding was ever prevalent over sprintf stuff it’s because it’s childlike in its simplicity. It’s horrible but a first month student could follow it. Not so for sprintf