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/stfcfanhazz Jan 06 '22

I agree sprintf is a better approach for complex interpolations or for when values need to be retrieved from methods etc because the alternative is a melting pot of quotes ' and periods . which can be a pain to parse mentally. But simple concatenations are fine too e.g. appending one string to another.

1

u/grsftw Jan 06 '22

Fair enough. I do this for sure:

d(“thisVar.value=“ . $thisVar[‘something’])