PHP: Don’t repeat parameters using sprintf()

While missing a C# method String.Format() I’ve found a similar function in PHP, i.e. sprintf(). But since this function is slightly different from String.Format() it is not obvious how to avoid duplicating the same parameters.

For instance how to re-write an example below without passing $url and $title twice.

$link = sprintf('<a href="%s" title="%s">%s</a> (%s)</li>',
              $url, $title, $title, $url);

The answer is less obvious compare to C# but still pretty handy:

$link = sprintf('<a href="%1$s" title="%2$s">%2$s</a> (%1$s)',
              $url, $title);

In both cases echo $link give the same output like:

<a href="http://www.google.com/" title="Google">Google</a> (http://www.google.com/)

but the second way makes the code more elegant 🙂 .

No Comment

No comments yet

Leave a reply