1.Sign specifier:
By default browsers only display - sign in front of negative numbers. + sign in front of positive numbers are omitted. But it is possible to instruct the browser to display + sign in front of positive numbers by using sign specifier. For example:
$num1=10;
$num2=-10;
$output=sprintf("%d",$num1);
echo "$output<br>";
$output=sprintf("%d",$num2);
echo "$output";
Output:
10
-10
Here the + sign before the positive number is omitted. However, if we put a + sign after % character of %d then the omission no longer takes place.
$num1=10;
$num2=-10;
$output=sprintf("%+d",$num1);
echo "$output<br>";
$output=sprintf("%+d",$num2);
echo "$output";
Output:
+10
-10
2.Padding specifier:
The padding specifier adds certain number of characters to the left or right of the output. The characters may be empty spaces, zeroes or any other ASCII character.
For example,
$str="hello";
$output=sprintf("[%10s]",$str);
echo $output;
Source code output:
[ hello] //Total length of 10 positions,first five being empty spaces and remaining five being "hello"
HTML output:
[ hello] //HTML displays only one empty space and collapses the rest, you have to use the <pre>...</pre> tag in the code for HTML to preserve the empty spaces.
Putting a negative sign left justifies the output:
$output=["%-10s",$string];
echo $output;
Source code output:
[hello ]
HTML output:
[hello ]
Putting 0 after % sign replaces empty spaces with zeroes.
$str="hello";
$output=sprintf("[%010s]",$str);
echo $output;
Output:
[00000hello]
Left justification
$output=sprintf("[%-010s]",$str);
Output:
[hello00000]
Putting ' followed by any ASCII character like * after % results in the display of that ASCII character instead of empty spaces
$str="hello";
$output=sprintf("[%'*10s]",$str);
echo $output;
Output:
*****hello
Left justification:
$output=sprintf("[%-'*10s]",$str);
echo $output;
Output:
hello*****