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

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.