Since we're talking about sprintf()
and its invaluable assistance in formatting translated messages, we should cover the cases where you want to supply it with more than one bit of data. If you've got your multi-lingual "mojo" going on, you will remember that many languages use a different word order than English (for example, noun and then adjective), and this may affect your messages. You can still rely on the sprintf()
function, but we need to follow sprintf
's rules for argument swapping. If we leave translations out of this for a moment, we can see that argument swapping allows us to specify exactly where the additional arguments get placed into the format string:
$msg_v1 = 'They were %1$s %2$s.'; $msg_v2 = 'The %2$s were %1$s.'; print sprintf($msg_v1, 'large','dogs'); // They were large dogs. print sprintf($msg_v2, 'large','dogs'); // The dogs were large.
As a mnemonic, the original %s
is still hidden in there, but now it has 1$
or 2$
sandwiched in between...