How to use % character within sprintf in PHP

When using the sprintf function in PHP to concatenate strings or variables, you may encounter an error when trying to include a % character in the string itself. This can be problematic if you want to display a percentage or use the % character for formatting purposes.

For example, let’s say you have the following code:

echo sprintf( "Get this %s for %50 off", 'tshirt' );

This code would throw a PHP error because it considers %5 to be a placeholder and expects an additional argument to replace it with.

Uncaught ArgumentCountError: 3 arguments are required, 2 given 

To fix this issue, you can use the %% sequence to represent a single % character.

Here’s the corrected code:

echo sprintf( "Get this %s for %%50 off", 'tshirt' );

By using %% instead of a single %, you can now include the % character in the string without causing any errors.

If you have a variable that contains a percentage and you want to escape it before using sprintf, you can create a custom function to handle the escaping process. Here’s an example of such a function:

function esc_sprintf( $str ) {
   return str_replace( '%', '%%', $str );

You can then use this function to escape the % character in your variable before passing it to the sprintf function. This ensures that the % character is properly handled and doesn’t cause any errors.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up Next:

How to Disable Dark Mode for Chrome and Any App on macOS

How to Disable Dark Mode for Chrome and Any App on macOS