Formatting PHP Strings with printf and sprintf
Like many other languages, PHP features the versatile printf() and sprintf() functions that you can use to format strings in many different ways. These functions are handy when you need convert data between different formats — either to make it easy for people to read, or for passing to another program.
PHP features many other functions to format strings in specific ways — for example, the date() function is ideal for formatting date strings. However, printf() and sprintf() are great for general-purpose formatting.
In this tutorial you look at how to work with printf() and sprintf() to format strings.
A simple printf() example
The easiest way to understand printf() is to look at an example. The following code displays a string containing 2 numbers:
// Displays "Australia comprises 6 states and 10 territories" printf( "Australia comprises %d states and %d territories", 6, 10 );
Notice how the first %d in the string is replaced with the first argument after the string ( 6 ), while the second %d is replaced with the second argument ( 10 ). Here’s how it works:
- The first argument is always a string, and is called the . The format string contains regular text, as well as some optional (the %d s in this example).
- Each format specifier begins with a % (percent) sign. It takes an additional argument after the format string, formats the argument in a certain way, and inserts the result into the final string, which is then displayed in the Web page.
Type specifiers
The example above uses the %d format specifier. This formats an argument as a signed decimal integer. The ‘d’ is known as a , and printf() supports a wide range of them. Here’s a full list of type specifiers:
b Format the argument as a binary integer (e.g. 10010110 ) c Format the argument as a character with the argument’s ASCII value d Format the argument as a signed decimal integer e Format the argument in scientific notation (e.g. 1.234e+3 ) f Format the argument as a floating-point number using the current locale settings (e.g. in France a comma is used for the decimal point) F As above, but ignore the locale settings o Format the argument as an octal integer s Format the argument as a string u Format the argument as an unsigned decimal integer x Format the argument as a lowercase hexadecimal integer (e.g. 4fdf87 ) X Format the argument as an uppercase hexadecimal integer (e.g. 4FDF87 )
Here’s a simple example of type specifiers in action:
printf( "Here's the number %s as a float (%f), a binary integer (%b), an octal integer (%o), and a hex integer (%x).", 543.21, 543.21, 543.21, 543.21, 543.21 );
Here's the number 543.21 as a float (543.210000), a binary integer (1000011111), an octal integer (1037), and a hex integer (21f).
Sign specifier
Ordinarily, printf() only puts a sign symbol in front of negative numbers, not positive numbers:
printf( "%d", 36 ); // Displays "36" printf( "%d", -36 ); // Displays "-36"
If you’d rather printf() also put a + symbol in front of positive numbers, you can add the , + , before the type specifier:
printf( "%+d", 36 ); // Displays "+36" printf( "%+d", -36 ); // Displays "-36"
Padding
printf() lets you pad out an argument value to a fixed width. You can use any character you like for the padding, and you can pad to the left or the right of the value. Padding is useful for adding leading zeroes to numbers, and for right-aligning strings.
To add padding, insert a between the ‘%’ character and the type specifier. A padding specifier takes the format:
- can be a zero or a space. If you miss it out, spaces are used. If you want to pad using a different character, write an apostrophe ( ‘ ) followed by the character to use.
- is the number of characters to pad the value out to. A positive number adds padding to the left; a negative number adds padding to the right.
Here are some padding examples:
printf( "%04d", 12 ); // Displays "0012" printf( "%04d", 1234 ); // Displays "1234" printf( "%04d", 12345 ); // Displays "12345" printf( "% 10s", "Hello" ); // Displays " Hello" printf( "%10s", "Hello" ); // Displays " Hello" printf( "%'*10s", "Hello" ); // Displays "*****Hello" printf( "%'*-10s", "Hello" ); // Displays "Hello*****"
Notice that, in the 3rd example, the padding specifier doesn’t truncate the value to 4 characters. Padding specifiers only add characters.
Number precision
When using the f or F type specifier to format floats, PHP defaults to a precision of 6 decimal places:
printf( "%f", 123.456 ); // Displays "123.456000"
To specify a different precision, you can use a . This is a dot ( . ) followed by the number of decimal places to use, and it goes right before the type specifier. For example:
printf( "%.2f", 123.456 ); // Displays "123.46" printf( "%.10f", 123.456 ); // Displays "123.4560000000" printf( "%.0f", 123.456 ); // Displays "123"
If you use a padding specifier with a precision specifier then printf() pads the entire value, including the decimal point and decimal digits, to the specified length:
printf( "%08.2f", 123.456 ); // Displays "00123.46"
If you use a precision specifier with the s type specifier then printf() truncates the string value to the specified number of characters:
printf( "%.2s", "Hello" ); // Displays "He"
Argument swapping
By default, the first format specifier in the format string is used with the first argument after the format string, the second format specifier is used with the second argument, and so on. However, you can change this ordering if you like.
To do this, place a number followed by a dollar ( $ ) symbol between the % and the type specifier. For example:
// Displays "Australia comprises 10 territories and 6 states" printf( 'Australia comprises %2$d territories and %1$d states', 6, 10 );
In the above example, the first format specifier is %2$d . This means: “Take the second argument after the format string and display it as a decimal integer”. The second format specifier, %1$d , reads: “Take the first argument after the format string and display it as a decimal integer”. So the arguments are used in a different order.
In the above example, the format string is enclosed by single quotes rather than double quotes. This prevents each dollar ( $ ) symbol in the string from being interpreted as starting a PHP variable name. (You can find out more about this in Creating PHP Strings.)
Storing the result in a variable
So what about sprintf() ? This function is identical to printf() , except that rather than directly outputting the result, it returns it so that you can store it in a variable (or otherwise manipulate it). This is useful if you want to process the result before displaying it, or store it in a database. Here’s an example:
$result = sprintf( "Australia comprises %d states and %d territories", 6, 10 ); // Displays "Australia comprises 6 states and 10 territories" echo $result;
Other related functions include fprintf() for writing the result to a stream (such as a file), and vprintf()/vsprintf()/vfprintf() , which work with an array of values to format instead of an argument list.
In this article you’ve learned how to use PHP’s printf() , sprintf() and related functions to format strings. You’ve:
- Seen how format strings and format specifiers work
- Looked at the available type specifiers and the sign specifier
- Seen how to pad the result
- Learned how to specify number precision, and
- Looked at argument swapping.
You now know how to format strings in all sorts of useful ways. You can produce strings that are easy for users to read, or that are suitable for passing to other programs. Happy coding!
Reader Interactions
Leave a Reply Cancel reply
To include a block of code in your comment, surround it with
.
tags. You can include smaller code snippets inside some normal text by surrounding them with .
tags.
Allowed tags in comments: .
Primary Sidebar
Hire Matt!
Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!
Stay in Touch!
Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.