phpprintf

How do sign specifiers and padding specifiers work with printf() and sprintf() in PHP?


I am studying about printf,sprintf and i didnt understand few points, if can some one please help me understand thos points,

At This Link at PHP Manual:

There are explanations are numbered from one to six:

What i didnt understand is: The First and The Second(1(sign specifier), 2(padding specifier)), if can some one please help me with example for thos i will be very thankful.


Solution

  • The sign specifier forces a sign, even if it's positive. So, if you have

    $x = 10;
    $y = -10;
    printf("%+d", $x);
    printf("%+d", $y);
    

    You'll get:

    +10
    -10
    

    The padding specifier adds left padding so that the output always takes a set number of spaces, which allows you to align a stack of numbers, useful when generating reports with totals, etc.

     $x = 1;
     $y = 10;
     $z = 100;
     printf("%3d\n", $x);
     printf("%3d\n", $y);
     printf("%3d\n", $z);
    

    You'll get:

       1
      10
     100
    

    If you prefix the padding specifier with a zero, the strings will be zero padded instead of space padded:

     $x = 1;
     $y = 10;
     $z = 100;
     printf("%03d\n", $x);
     printf("%03d\n", $y);
     printf("%03d\n", $z);
    

    Gives:

     001
     010
     100