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

9

u/Plastonick Jan 05 '22

I'll put strtr in the mix!

$vars = [
	'{spouse}' => $spouse, 
	'{petNum}' => $petNumber, 
	'{petType}' => $petType,
	'{emotion}' => $emotion
];

$template = 'My {spouse} has {petNum} {petType} and that makes me {emotion}';

$s = strtr($template, $vars);

1

u/eklingen Jan 24 '22

Interesting approach, but it really seems like unnecessary steps when PHP has built-in variable interpolation in the same format.

2

u/Plastonick Jan 24 '22

Ah you say that, but this allows for making the templates variable.

As in, do you want to let the customer decide some "success" message? Let them choose their success "template" and we can interpolate the values afterward!

A basic example:

function buildMessage(string $template)
{
	$vars = [
	    '{targetName}' => $this->getTargetName(), 
	    '{compliment}' => $this->getCompliment(), 
	    '{yourName}' => $this->getYourName(),
	];

	return strtr($template, $vars);
}

echo buildMessage('Congrats {targetName}, you did {compliment}! From {yourName}.');

// or a simple message
echo buildMessage('Well done {targetName}! From {yourName}.');

I admit, I'd normally just use double quotes and interpolated variables where the template is fixed, but I think the above is really useful.