PHP vsprintf()
Function
Example
Writing a formatted string to a variable:
Definition and Usage
The vsprintf() function writes a formatted string to a variable.
Unlike sprintf(), the arguments in vsprintf() are contained within an array. The array elements will be inserted at the percent (%) signs in the main string. This function processes step by step. At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, and so on.
Note: If there are more % signs than arguments, you must use placeholders. Placeholders are inserted after the % sign and consist of a number and a "$". See Example 2.
Tip: Related functions: fprintf(), vfprintf(), printf(), sprintf(), and vprintf()
Syntax
Parameter | Description |
---|---|
format | Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %<br> %b - Binary number<br> %c - Character corresponding to the ASCII value<br> %d - Signed decimal number (negative, zero, positive)<br> %e - Lowercase scientific notation (e.g., 1.2e+2)<br> %E - Uppercase scientific notation (e.g., 1.2E+2)<br> %u - Unsigned decimal number (greater than or equal to 0)<br> %f - Floating point number (locale aware)<br> %F - Floating point number (non-locale aware)<br> %g - Shorter of %e and %f<br> %G - Shorter of %E and %f<br> %o - Octal number<br> %s - String<br> %x - Hexadecimal number (lowercase letters)<br> %X - Hexadecimal number (uppercase letters) Additional format values. Must be placed between % and the letter (e.g., %.2f): + (Adds a + or - sign before the number. By default, only negative numbers are marked, positive numbers are not marked)<br> ' (Specifies what to use as padding. Default is space. It must be used with a width specifier. For example: %'x20s (uses "x" as padding))<br> - (Left-justifies the variable value)<br> [0-9] (Specifies the minimum width of the variable value)<br> .[0-9] (Specifies the number of decimal places or the maximum string length) Note: If multiple format values are used, they must be used in the order shown above, without rearranging. |
argarray | Required. An array containing the arguments to be inserted at the % signs in the format string. |
Technical Details
Return Value: | Returns the array values as a formatted string. |
---|---|
PHP Version: | 4.1.0+ |
--- | --- |
More Examples
Example 1
Using the format value %f:
Example 2
Using placeholders:
Example 3
Demonstrating all possible format values using sprintf():
Example 4
Demonstrating string specifiers: