Formatting a number with leading zeros in PHP

I have a variable which contains the value 1234567 .

I would like it to contain exactly 8 digits, ie 01234567 .

Is there a PHP function for that?


Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad :

str_pad($value, 8, '0', STR_PAD_LEFT);

Given that the value is in $value:

  • To echo it:

    printf("%08d", $value);

  • To get it:

    $formatted_value = sprintf("%08d", $value);

  • That should do the trick


    echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
    
    链接地址: http://www.djcxy.com/p/62528.html

    上一篇: 将输出格式化为每行40个字符

    下一篇: 使用PHP中的前导零格式化数字