sprintf

sprintf is similar to printf however is used to return the result as a value for a variable to be used later rather than output immediately.

Here’s the difference you can test in your child themes functions file.

sprintf
add_action('loop_start','sprintf_example' );
function sprintf_example() {		
$output = sprintf('%s World', 'Hello' ); 
echo $output;
}
printf
add_action('loop_start','printf_test' );
function printf_test() {		
	printf('%s World', 'Hello' ); 
}

Both code snippets produce exactly the same result. The only difference is sprintf returns the value for the variable and printf outputs directly.

You can also write the code using sprintf like this:

add_action('loop_start','sprintf_example1' );
function sprintf_example1() {
$text = "Hello";		
$output = sprintf('%s World', $text ); 
echo $output;
}

And this:

add_action('genesis_after_header','sprintf_example2' );
function sprintf_example2() {
    $link = get_permalink();
    $text = "Hello";		
    $output = sprintf('%s World', $text ); 
printf( '<a href="%s">' . $output . '</a>', $link );
}

Or this:

add_action('wp_head','sprintf_example3' );
function sprintf_example3() {
    $link = get_permalink();
    $text = "sprintf";		
    $output = sprintf('%s Example', $text ); 
printf( '<a href="%s">%s</a>', $link, $output );
}

Related PHP Code

Was This Tutorial Helpful?

Free

$0

Access only to all free tutorials per month.



Monthly

$75

Access to 10 premium tutorials per month.


Tutorial Request


Includes code guarantee and coding support.

Yearly

$500

Access to 15 premium tutorials per month.


Monthly Tutorial Request


Includes code guarantee and priority coding support.