PHP sprintf() Function

PHP sprintf() Function

The sprintf() function in PHP is used to write a formatted string to a variable and returns a formatted string. PHP 4 and above versions support the sprintf() function.

The related functions are as follow: 

Syntax

sprintf (format, agr1, agr2, arg3...) 

Parameter

format(required)- This parameter specifies the string and how to format the variables in it.

The conversion specification of this parameter follows the given prototype: %[flags][width][.precision]specifier.

Flags

Flag Description
- Left-justify within the given field width and by default, its follows the right justification
+ It signifies the prefix positive numbers with a plus sign(+). By default, only negative is prefixed with a negative sign.
(space) It pads the result with spaces. This is the default.
0 It only left-pads numbers with zeros. With “s” specifiers this can also right-pad with zeros.
(char) It pads the result with the character (char).

Width

It signifies an integer that states how many characters (minimum) this conversion should result in.

Precision

  • e, E, f and F specifiers: The number of digits to be printed after the decimal point (by default, it is 6).
  • g and G specifiers: The maximum number of significant digits to be printed.
  • s specifier: It acts as a cutoff point, setting a maximum character limit to the string.

If the period is specified without an explicit value for precision, 0 is assumed.

Specifiers

Specifier Description
% It represents a literal percent character, and no other argument is required.
b In this, the argument is treated as an integer and presented as a binary number.
c In this, the argument is treated as an integer and presented as the character with that ASCII.
d In this, the argument is treated as an integer and presented as a (signed) decimal number.
e In this, the argument is treated as scientific notation. The precision specifier stands for the number of digits after the decimal point.
E It is like the “e” specifier, but it uses the uppercase letter.
f The argument is treated as a float and presented as a floating-point number (locale aware).
F The argument is treated as a float and presented as a floating-point number (non-locale aware). 
g It represents a general format.
G Unlike the “g” specifier but it also uses E and F.
o In this, the argument is treated as an integer and presented as an octal number.
s In this, the argument is treated and presented as a string.
u In this, the argument is treated as an integer and presented as an unsigned decimal number.
x The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Type Handling

Type Specifiers
String s
Integer d, u, c, o, x, X, b
double g, G, e, E, f, F

arg1(required)- This parameter represents the value to be inserted at the first %-sign in the format string.

arg2(optional)- This parameter represents the value to be inserted at the second %-sign in the format string.

arg++( optional)- This parameter represents the value to be inserted at the third, fourth, etc. %-sign in the format string.

Return

This function returns a string produced according to the formatting string format, or FALSE on failure.

Example 1

<?php
// initializing the number
$num = 134523;
echo "The number: ".$num;
// Returns a string according to the %f format
$text = sprintf("%f",$num);
// printing the sprint() function returned value
echo "\nThe sprintf() function will return: ".$text;
?> 

Output

The number: 134523
The sprintf() function will return: 134523.000000

Example 2

<?php
// initializing a positive number
$num1 = 126789;
// initializing a negative number
$num2 = -126789;
// initializing the character value
$char = 50; // The ASCII Character 50 is 2
echo"The ASCII Character for ".$char." is:". sprintf("%c",$char)."\n"; // return 2
echo "The signed decimal number for ".$num1." is:".sprintf("%d",$num1)."\n"; // will return a number 126789
echo "The signed decimal number for ".$num2." is:". sprintf("%d",$num2)."\n"; //will return a number -126789
?> 

Output

The ASCII Character for 50 is:2
The signed decimal number for 126789 is:126789
The signed decimal number for -126789 is:-126789 

Example 3

<?php
// initializing a positive number
$num1 = 126789;
// initializing a negative number
$num2 = -126789;
echo "The unsigned decimal number for ".$num1." is:".sprintf("%u",$num1)."\n";
echo "The unsigned decimal number for ".$num2." is:". sprintf("%u",$num2)."\n";
echo "The Floating-point number for ".$num1." is:".sprintf("%f",$num1)."\n";
echo "The Floating-point number for ".$num2." is:". sprintf("%F",$num2)."\n";
echo "The Shorter value of %e and %f ".$num1." is:".sprintf("%u",$num1)."\n";
echo "The Shorter value of %E and %f ".$num2." is:". sprintf("%u",$num2)."\n";
?> 

Output

The unsigned decimal number for 126789 is:126789
The unsigned decimal number for -126789 is:18446744073709424827
The Floating-point number for 126789 is:126789.000000
The Floating-point number for -126789 is:-126789.000000
The Shorter value of %e and %f 126789 is:126789
The Shorter value of %E and %f -126789 is:18446744073709424827 

Example 4

<?php
//initializing string 1
$str1 = "Hello";
// initializing string 2
$str2 = "Hello PHP";
echo sprintf("[%s]",$str1);
echo "\n";
echo sprintf("[%8s]",$str2);
echo "\n";
echo sprintf("[%'*8s]",$str1);
echo "\n";
echo sprintf("[%-8s]",$str2);
echo "\n";
echo sprintf("[%08s]",$str1);
echo "\n";
echo sprintf("[%8.8s]",$str2);
?> 

Output

[Hello]
[Hello PHP]
[***Hello]
[Hello PHP]
[000Hello]
[Hello PH] 

The sprintf() function in PHP is used to write a formatted string to a variable and returns a formatted string. PHP 4 and above versions support the sprintf() function.

The related functions are as follow: 

  • printf()
  • vprintf()
  • vsprintf() 
  • fprintf()
  • vfprintf()

Syntax

sprintf (format, agr1, agr2, arg3...) 

Parameter

format(required)- This parameter specifies the string and how to format the variables in it.

The conversion specification of this parameter follows the given prototype: %[flags][width][.precision]specifier.

Flags

Flag Description
- Left-justify within the given field width and by default, its follows the right justification
+ It signifies the prefix positive numbers with a plus sign(+). By default, only negative is prefixed with a negative sign.
(space) It pads the result with spaces. This is the default.
0 It only left-pads numbers with zeros. With “s” specifiers this can also right-pad with zeros.
(char) It pads the result with the character (char).

Width

It signifies an integer that states how many characters (minimum) this conversion should result in.

Precision

  • e, E, f and F specifiers: The number of digits to be printed after the decimal point (by default, it is 6).
  • g and G specifiers: The maximum number of significant digits to be printed.
  • s specifier: It acts as a cutoff point, setting a maximum character limit to the string.

If the period is specified without an explicit value for precision, 0 is assumed.

Specifiers

Specifier Description
% It represents a literal percent character, and no other argument is required.
b In this, the argument is treated as an integer and presented as a binary number.
c In this, the argument is treated as an integer and presented as the character with that ASCII.
d In this, the argument is treated as an integer and presented as a (signed) decimal number.
e In this, the argument is treated as scientific notation. The precision specifier stands for the number of digits after the decimal point.
E It is like the “e” specifier, but it uses the uppercase letter.
f The argument is treated as a float and presented as a floating-point number (locale aware).
F The argument is treated as a float and presented as a floating-point number (non-locale aware). 
g It represents a general format.
G Unlike the “g” specifier but it also uses E and F.
o In this, the argument is treated as an integer and presented as an octal number.
s In this, the argument is treated and presented as a string.
u In this, the argument is treated as an integer and presented as an unsigned decimal number.
x The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Type Handling

Type Specifiers
String s
Integer d, u, c, o, x, X, b
double g, G, e, E, f, F

arg1(required)- This parameter represents the value to be inserted at the first %-sign in the format string.

arg2(optional)- This parameter represents the value to be inserted at the second %-sign in the format string.

arg++( optional)- This parameter represents the value to be inserted at the third, fourth, etc. %-sign in the format string.

Return

This function returns a string produced according to the formatting string format, or FALSE on failure.

Example 1

<?php
// initializing the number
$num = 134523;
echo "The number: ".$num;
// Returns a string according to the %f format
$text = sprintf("%f",$num);
// printing the sprint() function returned value
echo "\nThe sprintf() function will return: ".$text;
?> 

Output

The number: 134523
The sprintf() function will return: 134523.000000

Example 2

<?php
// initializing a positive number
$num1 = 126789;
// initializing a negative number
$num2 = -126789;
// initializing the character value
$char = 50; // The ASCII Character 50 is 2
echo"The ASCII Character for ".$char." is:". sprintf("%c",$char)."\n"; // return 2
echo "The signed decimal number for ".$num1." is:".sprintf("%d",$num1)."\n"; // will return a number 126789
echo "The signed decimal number for ".$num2." is:". sprintf("%d",$num2)."\n"; //will return a number -126789
?> 

Output

The ASCII Character for 50 is:2
The signed decimal number for 126789 is:126789
The signed decimal number for -126789 is:-126789 

Example 3

<?php
// initializing a positive number
$num1 = 126789;
// initializing a negative number
$num2 = -126789;
echo "The unsigned decimal number for ".$num1." is:".sprintf("%u",$num1)."\n";
echo "The unsigned decimal number for ".$num2." is:". sprintf("%u",$num2)."\n";
echo "The Floating-point number for ".$num1." is:".sprintf("%f",$num1)."\n";
echo "The Floating-point number for ".$num2." is:". sprintf("%F",$num2)."\n";
echo "The Shorter value of %e and %f ".$num1." is:".sprintf("%u",$num1)."\n";
echo "The Shorter value of %E and %f ".$num2." is:". sprintf("%u",$num2)."\n";
?> 

Output

The unsigned decimal number for 126789 is:126789
The unsigned decimal number for -126789 is:18446744073709424827
The Floating-point number for 126789 is:126789.000000
The Floating-point number for -126789 is:-126789.000000
The Shorter value of %e and %f 126789 is:126789
The Shorter value of %E and %f -126789 is:18446744073709424827 

Example 4

<?php
//initializing string 1
$str1 = "Hello";
// initializing string 2
$str2 = "Hello PHP";
echo sprintf("[%s]",$str1);
echo "\n";
echo sprintf("[%8s]",$str2);
echo "\n";
echo sprintf("[%'*8s]",$str1);
echo "\n";
echo sprintf("[%-8s]",$str2);
echo "\n";
echo sprintf("[%08s]",$str1);
echo "\n";
echo sprintf("[%8.8s]",$str2);
?> 

Output

[Hello]
[Hello PHP]
[***Hello]
[Hello PHP]
[000Hello]
[Hello PH] 

Related Topics

PHP isset() function

PHP isset is used to check whether the variable is set or not.The PHP isset() function returns false if variable contains a NULL value. Syntax: isset(variable1, variable2….) Presentation of PHP isset: In...

2 minutes read.

PHP Comment

PHP commentis a line of code that is not executed. It is often used by developer to understand the code. PHP support single and multiple comments. In other language like C,...

1 minute read.

PHP foreach Loop

PHP foreach Loop with Example PHP foreach loop is used to loop through the associative arrays. Syntax: foreach($array as $key => $value) { //Statement } $array = associative array. $key = array key. &value =...

2 minutes read.

PHP array_intersect() function

The array_intersect () function in PHP is used to compute the intersection of arrays. It returns an array containing all the entries from array1 that are present in all the other arrays. Syntax array_intersect ( array $array1 , array $array2 [, array $... ]) Parameter array1(required)- This parameter...

1 minute read.

PHP array_reduce() Function

PHP array_reduce() Function The array_reduce() function in PHP reduces the array to a single value using by applying a callback function to the elements of the array. Syntax array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] ) Parameter array(required)- This parameter represents the input array. callback (required)- This...

1 minute read.

PHP array_diff_ukey() Function

The array_diff_ukey() function in PHP compares the keys from array1 against the keys from array2 and returns the difference containing all the entries from array1 that are not present in any of the other arrays. Syntax array_diff_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) Parameter array1(required)- This parameter signifies the...

1 minute read.

PHP array_search() Function

PHP array_search() Function The array_search() function in PHP searches the array for the specified value. This function returns the first corresponding key if the value is found. Syntax array_search ( mixed $needle , array $haystack [, bool $strict ])  Parameter needle(required)- This parameter represents the value to...

1 minute read.

PHP String

PHP string is a sequence of characters. It is used to store and manipulate text. We can specify a string literal in four ways: single quoted double quoted heredoc syntax ...

2 minutes read.

PHP str_word_count() Function

PHP str_word_count() Function The str_word_count() function in PHP counts the number of words inside the string and returns the information about words used in a string. String str_word_count( string $string [, int $format [, string $charlist ]] ) Parameter string(required)- This parameter represents the input string. format(required)- This parameterspecifies the...

2 minutes read.

PHP array_key_first() function

The array_key_first () function in PHP gets the first key of an array if the specified array is not empty. Syntax array_key_first(array;$array) Parameter array(required)- This parameter signifies the input array. Return This function returns the first key of the specified...

1 minute read.

PHP str_split() Function

PHP str_split() Function The str_split() function in PHP splits a string into an array. String str_split ( string $string [, int $split_length = 1 ] ) Parameter string(required)- This parameter represents the input string. split_length(optional)- This parameter signifies the maximum length of the chunk. The default value is 1. Return This function...

2 minutes read.

PHP convert_cyr_string() Function

PHP convert_cyr_string() Function The convert_cyr_string() function in PHP converts from one Cyrillic character-set to another. The supported characters set are given below: k - koi8-rw - windows-1251i - iso8859-5a - x-cp866d - x-cp866m...

1 minute read.

PHP empty() Function

PHP empty() Function The empty() function in PHP determines whether the specified variable is empty or not. The specified variable is considered empty if it does not exist or if its value is equal to FALSE. This function...

1 minute read.

PHP substr_count() Function

PHP substr_count() Function The substr_count() function in PHP counts the number of times a substring occurs in the specified string. Syntax substr_count ( string $haystack , string $needle [, int $offset  [, int $length ]] ) Parameter haystack(required)- This parameter signifies the string to search in. needle (required)- This parameter represents the substring to search...

1 minute read.

PHP stripslashes() Function

PHP stripslashes() Function The stripslashes() Function in PHP removes backslashes or un-quotes a quoted string. Syntax stripslashes ( string $str ) Parameter str(required)- This parameter signifies the input string. Return This function returns a string with backslashes stripped off and the double backslashes (\\) are made...

1 minute read.

PHP array_intersect_assoc() function

PHP array_intersect_assoc() function The array_intersect_assoc() function in PHP is used to compute the intersection of arrays with the help of an additional index check. It returns an array containing all the entries from array1 that are present...

1 minute read.

PHP strcasecmp() Function

PHP strcasecmp() Function The strcasecmp() function in PHP compares two strings. It is a binary-safe case-insensitive string function. Syntax strcasecmp ( string $str1 , string $str2 ) Parameter str1(required)- This parameter represents the first string. str2(required)- This parameter represents the second string. Return This function returns a value less than( <...

1 minute read.

PHP ksort() Function

PHP ksort() Function The ksort() function in PHP sorts an array by key while maintaining the keys. Syntax ksort(array & $array[,int $sort_flags = SORT_REGULAR] ) Parameter array(required)- This parameter represents the input array. sort_flags(optional)- This parameter is...

2 minutes read.

PHP is_real() Function

The PHP is_real () function in PHP is used to find whether the type of the specified variable is a float or not. It returns a Boolean value true if the parameter...

1 minute read.

PHP array_splice() Function

PHP array_splice() Function The array_splice() function in PHP is used to remove a portion of the array and replaces them with the elements of the replacement array. Syntax array_splice (array &$input, int $offset [, int $length = count($input) [, mixed $replacement = array() ]] ) Parameter input(required)- This array represents the...

2 minutes read.