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

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.

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

8

u/Meek_braggart Jan 05 '22

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

Not so messy.

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

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’])

13

u/txmail Jan 05 '22

I usually use {$varName} notation in double quotes. I would just assign the emotion before hand e.g. $s = "My {$spouse} has {$petNumber}...."

12

u/marioquartz Jan 05 '22

use concatenations that are impossible to understand easily.

For me is the inverse. Sprintf require count two times for each variable for understand the text. Concatenation requires zero counts.

"My %s" What is %s. Oh! i have to go the last part of the function and search which one.

Concatenation: "My ".$spouse. I have the answer instantaneously answered.

22

u/HolyGonzo Jan 05 '22 edited Jan 05 '22

PHP's variable interpolation simply makes it easier to read, in my opinion. It's more like natural language.

Imagine if you were talking to someone and you said, "My name is... I'll tell you in a second... and my job is.... I'll tell you that in a second, too. Gonzo and programmer."

Compare that to "My name is Gonzo and my job is programmer."

The use of sprintf() for basic string assembly is great when you don't have an alternative.

However, the string concatenation and interpolation makes it easy to read and ALSO easy to update. If I need to change the string to take out or add a variable, I don't need to insert a placeholder AND then figure out where to insert the value later.

I generally use sprintf() for shell scripts where I want some more advanced control over formatting/layout of content.

As far as -technical efficiency- goes, sprintf is more efficient than string concatenation or interpolation but since most PHP scripts are so short / tiny, small inefficiencies can be considered acceptable.

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.

12

u/sprain_mr Jan 05 '22

I love sprintf. But you have to know it first. The other syntax looks more like what a beginner would do as it‘s more obvious. I used to do that, too.

4

u/MDChristie Jan 05 '22

But why is it any better than the first syntax (or the similar but IMHO preferable "My {$spouse} has {$petNumber}....")?

The other syntax looks more like what a beginner would do as it‘s more obvious

Obvious is good. Quality code should be obvious and as easy to read as possible. If you're going to make something harder to read there should be a good reason for it.

Sure, if you're using sprintf for it's more power features, by all means. But if you're literally just joining a few strings it's cleaner to just concatenate/interpolate.

2

u/[deleted] Jan 13 '22

I love sprintf, always thought of it as kinda like a fill-in-the-blank. Also, template strings are easily translatable, much better for i18n, unlike the dynamic string generated via concatenation.

3

u/CyberJack77 Jan 05 '22

I love using sprintf. It can do way more than string concatenation and it makes my code better readable.

1

u/bobd60067 Jan 05 '22

For me, it's a mindset. That is, I think of the dot operator as ideal for (and intended for) simple string concatenation, whereas I think of sprintf as ideal for formatting (e.g., %8.4f for fixed point floats, or %04X for 4-digit hex, or %10s for fixed width strings).

I don't think there's a right or wrong answer just like there's no right or wrong way to use other php functions and operators.

1

u/TransientVoltage409 Jan 06 '22

The first programming language I ever learned was BASIC, which used string concatenation ('+') exclusively. Simple, easy. Later I learned C (where there is no string type at all) and printf. Not really better or worse IMO. Different. Far more power and flexibility if you need it, but not like you have to wade through a swamp to do something simple. By force of inertia I tend to use printf in the general case in PHP and Java too - I've written a lot of C - but it's just one tool in the box.

[Also in C, one can prefer snprintf to avoid buffer overflow, or a lovely version call asprintf that allocates the needed buffer on demand. Not relevant in PHP, but neat.]

1

u/kenlubin Jan 06 '22

I find named variables to be easier to read than positionally indexed variables in almost all cases. The major exception would be if the variables are interchangeable, like "WHERE foo IN (?, ?, ?, ?)".

1

u/Far-Praline1218 Jan 09 '22

I've seen code of numerous frameworks like Symfony for instance, that use sprintf in many cases like for exception messages. I don't think this function has a bad rep.

1

u/itemluminouswadison Jan 05 '22

I think it's just not knowing about it and why it's great

Experience leads to wanting to extract messages as constants while leaving room for replacements

String.format in java is the same. Wanting to do any i18n might use this too

So yeah i think it's just novice-ness and once people start using it, they appreciate it

1

u/kAlvaro Jan 05 '22 edited Jan 06 '22

I can of course only speculate. But my feeling is that most developers don't care too much about the language basics and just dive into advanced stuff as soon as possible. That's even more noticeable when there's a framework involved in the learning process. So they're just unaware of the possibilities.

1

u/jstormes Jan 05 '22

I use both. It depends on what I am doing and how well it "fits".

I started out as a C developer, even developing code in C that linked into PHP, so both just seem natural. I tend to use sprintf for logging type work and imbedded concatenation when doing HTML type work.