r/PHPhelp • u/grsftw • 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
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";