• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP SITES

2784

Original Genesis Tutorials & 6000+ Guaranteed Code

Snippets

  • Consultation
  • Full Access
  • Log in

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

  • printf
  • Variable
  • 12 Code Examples for using sprintf & sprintf

PHP Functions

Reader Interactions

Leave a Reply Cancel reply

You must be logged in to post a comment.

Primary Sidebar

Code written by Brad Dalton specialist for Genesis, WooCommerce & WordPress theme customization. Read More…

Advertise · WPEngine · Genesis · Log in

  • Access Problems
  • Account Details
  • Consulting
  • Tags