There's a pair of string functions that are particularly useful when you want to format data for display (such as when you're formatting numbers in string form): printf and sprintf. The printf function echoes text directly, and you assign the return value of sprintf to a string. Here's how you use these functions (items in square brackets, [ and ], in function specifications like this one are optional): printf (format [, args]) sprintf (format [, args]) The format string is composed of zero or more directives: characters that are copied directly to the result, and conversion specifications. Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
Here are the possible type specifiers:
These functions take a little getting used to, especially when you're formatting floating point values. For example, a format specifier of %6.2 means that a floating point number will be given six places in the display, with two places behind the decimal point. Here's an example that puts printf and sprintf to work: <?php printf("I have %s apples and %s oranges.\n", 4, 56); $year = 2005; $month = 4; $day = 28; printf("%04d-%02d-%02d\n", $year, $month, $day); $price = 5999.99; printf("\$%01.2f\n", $price); printf("%6.2f\n", 1.2); printf("%6.2f\n", 10.2); printf("%6.2f\n", 100.2); $string = sprintf("Now I have %s apples and %s oranges.\n", 3, 5); echo $string; ?> In this example, we're formatting simple integers as strings, aligning floating-point numbers vertically so the decimal point lines up, and so on. Here's what you see when you run this script at the command line: I have 4 apples and 56 oranges. 2005-04-28 $5999.99 1.20 10.20 100.20 Now I have 3 apples and 5 oranges. NOTE Another function useful for formatting numbers is number_format(). |