What is the meaning of %s, %1$s etc.?

The question:

From a Q&A Thread I’ve came to meet with some old things, but I’m afraid, I found myself in a condition that, I still don’t know the meaning of them and don’t know why to use them.

  • %1$s – (found to load widget id)
  • %2$s – (found to load widget class/classes)
  • %s – (found here)

And how the following things work? I mean what’s the explanation of the code-format?

  • !Website::getThemeOption("format_post/{$post_format}/content/hide")): – (found here)
  • if( !wp_verify_nonce( $_POST['my_noncename'] ) plugin_basename( __FILE__ ) ) return; – (found here)

This question can go on and on…, I know. But things like these are not clearly explained anywhere. I, not just want their meaning and purposes, but want some inner/core explanation so that I can understand their motives and how they works.

And also, if such things are already clearly defined in Codex, I’d love to read them. And would love to have a list of such curious things if such a list is already sorted out.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

This is really more of a general PHP programming question and might get closed for that reason. But before that happens, let’s see if I can’t clear some of this up for you.

Those strings that start with % signs are in “printf format”. For example, %2$s translates to “replace this token with the second parameter, and treat it like a string”.

When you see a variable in curly braces inside a string, like "Today is {$day}", that’s the same as putting the variable there without curly braces, like "Today is $day". But formatting the variable like this makes it stand out, so it’s more clear there’s a variable there. It also prevents other characters next to the variable name from getting interpreted as part of the name. Without curly braces, would PHP know what to do with "Your robot name would be {$firstName}Number5"? It would see "$firstNameNumber5" and look for a variable named $firstNameNumber5 instead of simply $firstName.

I’m not sure what you’re asking about in the last example. Is it the __FILE__ you’re confused by? That’s a PHP Magic Constant that gets replaced with the full path to the file that bit of code is in.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment