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

PHP addslashes() Function The addslashed() function in PHP is used to return a string with backslashes in front of predefined characters. This function is only used with some characters which are...

1 minute read.

PHP array_flip() function

PHP array_flip() function The array_flip() function in PHP exchanges all keys with their associated values in an array and returns an array in flip order. If the specified value has several occurrences, the latest key will be...

1 minute read.

PHP is_scalar() Function

PHP is_scalar() Function The is_scalar() function in PHP finds whether a variable is a scalar or not. It returns a Boolean value TRUE if the parameter var is scalar, else it returns FALSE. Scalar variables are those containing an integer, float, string or boolean. This...

1 minute read.

WordPress Plugin

WordPress Plugin is a process used to add or extend the functionality which can be enabled or disabled, and it does not interfere with the software and its code. WordPress is lightweight and smooth...

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

The PHP is_int() function in PHP is used to  find whether a variable is an integer or not. It returns a Boolean value true if the parameter var is integer else it...

1 minute read.

PHP strripos() Function

PHP strripos() Function The strripos() function in PHP finds the position of the last occurrence of a substring in the specified string. It is a case-insensitive and binary-safe function. Syntax strripos ( string $haystack , mixed $needle [, int $offset ] ) Parameter haystack(required)- This parameter signifies the...

1 minute read.

PHP var_dump() Function

PHP var_dump() Function The var_dump() function in PHP is used to dump the information about a variable. It displays the structured information (arrays and objects) about one or more expressions. This function is also effective...

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

The PHP is_countable() function in PHP is used to  find whether a variable is countable or not. It returns a Boolean value true if the parameter var is countable else it returns false. Syntax is_countable ( mixed...

1 minute read.

PHP asort() function

PHP asort() function The asort() function in PHP is used to sort an array while maintaining the index association. Syntax asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  array(required)- This parameter represents the input array to sort. sort_flags (optional)- This parameter is used to...

1 minute read.

PHP array_shift() Function

PHP array_shift() Function The array_shift() in PHP shifts the first value of the array off. This function returns the same value after shortening the array by one element and moving everything. Syntax array_shift ( array &$array )  Parameter array(required)- This parameter represents the input array Return This function returns...

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

PHP array_merge_recursive() Function The array_merge_recursive() function  in PHP merges the elements of one or arrays together and returns the resulting array. Syntax array_merge_recursive (array $array  , [ array $... ] ) Parameter array(required)- This parameter specifies the input array ….(optional)- It represents more arrays to...

1 minute read.

PHP sha1() Function

PHP sha1() Function The sha1() in PHP calculates the SHA-1 hash of a string. Syntax sha1 ( string $str [, bool $raw_output = FALSE ] )  Parameter str (required)- This parameter represents the input string. raw_output(optional)- This parameter takes Boolean value and returns the digest in raw binary format...

1 minute read.

PHP convert_uuencode() Function

PHP convert_uuencode() Function The convert_uuencode() function in PHP is used to encode a string and returns the uuencoded data. Syntax convert_uuencode ( string $data ) Parameter data(required)- This parameter represents the data to be encoded. Return This function returns the uuencoded data or FALSE on failure. Example 1 <?php //...

2 minutes read.

PHP sha1_file() Function

PHP sha1_file() Function The sha1_file() in PHP calculates the sha1 hash of a file and returns the hash (40-character hexadecimal number). Syntax sha1_file ( string $filename [, bool $raw_output] )  Parameter filename(required)- This parameter represents the filename of the file to hash. raw_output(optional)- This...

1 minute read.