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

PHP next() Function The next() function in PHP advances or moves the internal array pointer one place forward and returns the next array value. Syntax next ( array &$array ) Parameter array(required)- This parameter represents the input array. Return This parameter returns the next array value...

1 minute read.

PHP strtoupper() Function

The strtoupper() function in PHP is used to convert a string to uppercase. This function is binary-safe. The related functions are as follows: strtolower()lcfirst()ucfirst()ucwords() Syntax strtoupper ( string $string ) Parameter string(required)- This parameter represents the input string. Return This function returns a string with all alphabetic...

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.

PHP var_export() Function

PHP var_export() Function The var_export() function in PHP is used to get the structured information for the specified variable. This function outputs or returns a parsable string representation of a variable. This function is similar to...

1 minute read.

PHP unserialize() Function

PHP unserialize() Function The unserialize() function in PHP takes a single serialized variable and converts it back into a PHP value. Syntax unserialize ( string $str [, array $options ] ) Parameter value(required)- This parameter represents the serialized string. options(optional)- This parameter signifies any options to be...

1 minute read.

PHP strchr() Function

PHP strchr() Function The strchr() function in PHP searches for the first occurrence of the specified string inside another string. It is a binary-safe case -sensitive function and is the alias of strstr() function. Syntax strstr ( string $haystack , mixed $needle [, bool $before_needle] ) Parameter haystack(required)-...

1 minute read.

PHP intval() Function

The intval() Function in PHP is used to get the integer value for the given variable. This function should not be used on objects. Else it will emit an E_NOTICE level error and return 1. Syntax intval...

1 minute read.

PHP array_walk() Function

PHP array_walk() Function The array_walk() function in PHP is used to apply the user-defined callback function to each element of the array. This function returns a Boolean TRUE on success or FALSE on failure. Syntax array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] ) Parameter array(required)- This array represents...

1 minute read.

PHP range() Function

PHP range() Function The range () function in PHP is used to create an array containing a range of elements. Syntax range ( mixed $start , mixed $end [, number $step = 1 ] ) Parameter start(required)- This parameter represents the first value of the sequence. end(required)- This parameter represents the...

1 minute read.

PHP strrrev() Function

PHP strrrev () Function The strrev() function in PHP reverses a string. Syntax strrev ( string $string ) Parameter string(required)- This parameter represents the input string to be reversed. Return This function returns the reversed string. Example 1 Output Initial string: Hello...

1 minute read.

PHP array_product() Function

PHP array_product() Function The array_product() function in PHP calculates the product of values in an array. Syntax array_product ( array $array ) Parameter array(required)- This parameter represents the input array. Return This function returns the product of the array elements as an integer or float....

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

PHP wordwrap() Function The wordwrap() Function wraps a string to a given number of characters using a string break character. Syntax wordwrap ( string $str [, int $width [, string $break  [, bool $cut  ]]] ) Parameter str(required)- This parameter specifies the input string.       width(optional)- This parameter represents the number of...

1 minute read.

PHP end() function

PHP end() function The end() function in PHP sets the internal pointer of an array to its last element. This function returns the value of the last element Syntax end ( array &$array )   Parameter array (required)– This parameter represents the input array. Return This function returns...

1 minute read.

Python main() function

What is a main() function? In most of the programming languages, there is this one special function i.e., main() which is executed firstly everytime when we run the program. The special...

6 minutes read.

PHP str_getcsv() Function

PHP str_getcsv() Function The str_getcsv() function in PHP parses a CSV string into an array and returns an array containing the fields read. Syntax str_getcsv ( string $input [, string $delimiter [, string $enclosure [, string$escape ]]] ) Parameter input(required)- This parameter represents the string to parse. delimiter(optional)- This parameter signifies...

1 minute read.

PHP convert_uudecode() Function

PHP convert_uudecode() Function The convert_uudecode() function in PHP decodes a uuencoded string. Syntax convert_uudecode ( string $data ) Parameter data- This parameter represents the uuencoded data. Return This function returns the decoded data as a string or FALSE on failure. Example 1 <?php // initializing the string $str...

1 minute read.

PHP Variables

PHP Variable is the name of memory location used to hold the data.  In PHP, variable starts with $ symbol. Rules for PHP Variables. Variable starts with $ sign. Variable name...

2 minutes read.