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 strcoll() Function

PHP strcoll() Function The strcoll() function in PHP compares two strings. This function is case-sensitive but not binary-safe. It uses the current locale for doing the comparisons. Syntax strcoll ( string $str1 , string $str2 ) Parameter str1(required)- This parameter represents the first string. str2(required)- This parameter...

1 minute read.

PHP While Loop

PHP while loop is used to run the same block of code until a condition is met. It should be used if number of iteration it not known. Syntax: <?php while (condition){   //Code...

1 minute read.

PHP array_fill() function

PHP array_fill() function The array_fill() function in PHP fills an user-defined array with num entries of the value that of specified values parameter, where the keys start at the start_index parameter. Syntax array_fill ( int $start_index , int $num , mixed $value ) Parameter start_index(required)- This parameter represents the first index of the...

1 minute read.

PHP strstr() Function

PHP strstr() Function The strstr() function in PHP finds the first occurrence of a string. It returns part of the parameter haystack string starting from and including the first occurrence of needle to the end of the haystack parameter. This function is case-sensitive.  Syntax strstr ( string $haystack , mixed $needle [, bool $before_needle] )  Parameter  haystack(required)-...

2 minutes 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 soundex() Function

PHP soundex() Function The soundex() function in PHP Calculates the soundex key(four character long alphanumeric string that represent English pronunciation of a word) of a string. Syntax soundex ( string $str ) Parameter str(required) – This parameter represents the input string. Return This function returns the soundex...

1 minute read.

PHP array_diff_key () Function

PHP array_diff_key () Function The array_diff_key () Function in PHP compares the keys from array1 against the keys from arrays. It returns an array containing all the entries from array1 whose keys are absent from all other arrays. This function is like array_diff () except that...

1 minute read.

PHP strtr() Function

PHP strtr() Function The strtr() function in PHP translates or replaces certain characters in a string. Syntax strtr ( string $str , string $from , string $to ) or strtr ( string $str , array $replace_pairs ) Parameter str(required)- This parameter specifies the string to translate from(required)- This parameter represents the string being translated to the parameter ‘to’. to(required)- It specifies what...

1 minute read.

PHP lcfirst() Function

PHP lcfirst() Function The lcfirst() function in PHP converts the first character of a string to lowercase if that character is alphabetic. Syntax lcfirst ( string $str ) Parameter str(required)- This parameter signifies the input string. Return This function returns a string with the...

1 minute read.

PHP Multidimensional Array

An array of arrays is called multidimensional array. It is used to store the data in a tabular form. It is represented in the form of matrix (row*column). Example: We can store...

2 minutes read.

PHP array_map() Function

PHP array_map() Function The array_map() function  in PHP is used to return an array containing the results of applying the user-defined callback function over the elements of one or more arrays. Syntax array_map ( callable $callback , array $array1 [, array $... ] )  Parameter callable(required)- This parameter...

1 minute read.

PHP nl2br() Function

PHP nl2br() Function The nl2br() function in PHP inserts HTML line breaks before all newlines in a string. Syntax nl2br ( string $string [, bool $is_xhtml] ) Parameter sting(required)- This parameter specifies the input string. is_xhtml(optional)- This parameter states whether to use XHTML compatible line breaks...

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 addcslashes() Function

The addcslashed() function in PHP is used to add quote string with slashes in a C style. It is case-sensitive function.  Syntax addcslashes (str, charlist ) Parameter str(required)- This parameter represents the string to be escaped. charlist(required)-...

1 minute read.

PHP compact() function

PHP compact() function The compact() function in PHP is used to create an array containing variables and their values. It returns the output array whose keys are the variable names, and their corresponding values are...

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 array_intersect_uassoc() function

The array_intersect_uassoc () function in PHP is used to compute the intersection of arrays with the help of an additional index check, comparing indexes by a callable function. It returns an array containing...

1 minute read.

PHP sizeof() Function

PHP sizeof() Function The sizeof() function in counts all elements and return the size of the array. This function is an alias of count(). Syntax sizeof( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )  Parameter array_or_countable(required)– This parameter represents the input array or countable object. mode(optional)-...

1 minute read.

PHP sort() Function

PHP sort() Function The sort() function in PHP sorts an array where the elements will be arranged from lowest to highest. Syntax sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  Parameter array(required)- This parameter represents the input array. sort_flags (optional)- This parameter is used to modify the...

1 minute read.

PHP str_replace() Function

PHP str_replace() Function The str_replace() function in PHP replaces all occurrences of the search string with the specified replacement string. This function is case-sensitive. Syntax str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) Parameter search(required)- This parameter signifies the value to search. replace(required)-...

1 minute read.